blob: 50882737c304b1ecf45591caed4ee82efdf28a3d [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
Steven Morelande5349192023-04-24 23:54:59 +0000183 user nobody
Steven Moreland6f5333a2017-11-13 15:31:54 -0800184
185service A something
186 class second
Steven Morelande5349192023-04-24 23:54:59 +0000187 user nobody
Steven Moreland6f5333a2017-11-13 15:31:54 -0800188 override
189
190)init";
191
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900192 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800193 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900194 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
Steven Moreland6f5333a2017-11-13 15:31:54 -0800195 ASSERT_EQ(1, std::distance(service_list.begin(), service_list.end()));
196
197 auto service = service_list.begin()->get();
198 ASSERT_NE(nullptr, service);
199 EXPECT_EQ(std::set<std::string>({"second"}), service->classnames());
200 EXPECT_EQ("A", service->name());
201 EXPECT_TRUE(service->is_override());
Tom Cherryad54d092017-04-19 16:18:50 -0700202}
203
Bart Van Assche5d188912022-11-14 09:30:51 -0800204TEST(init, StartConsole) {
Jiyong Park5b7a51a2022-12-20 09:18:49 +0900205 if (GetProperty("ro.build.type", "") == "user") {
206 GTEST_SKIP() << "Must run on userdebug/eng builds. b/262090304";
207 return;
208 }
Daniel Rosenbergb8baa8d2023-04-07 13:02:42 -0700209 if (getuid() != 0) {
210 GTEST_SKIP() << "Must be run as root.";
211 return;
212 }
Bart Van Assche5d188912022-11-14 09:30:51 -0800213 std::string init_script = R"init(
214service console /system/bin/sh
215 class core
Jiyong Parkae412802022-12-15 16:29:01 +0900216 console null
Bart Van Assche5d188912022-11-14 09:30:51 -0800217 disabled
218 user root
219 group root shell log readproc
Bart Van Assche3b21d952022-11-22 16:53:05 -0800220 seclabel u:r:shell:s0
Bart Van Assche5d188912022-11-14 09:30:51 -0800221 setenv HOSTNAME console
222)init";
223
224 ActionManager action_manager;
225 ServiceList service_list;
226 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
227 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
228
229 auto service = service_list.begin()->get();
230 ASSERT_NE(service, nullptr);
231 ASSERT_RESULT_OK(service->Start());
232 const pid_t pid = service->pid();
233 ASSERT_GT(pid, 0);
Bart Van Assche3b21d952022-11-22 16:53:05 -0800234 EXPECT_NE(getsid(pid), 0);
Bart Van Assche5d188912022-11-14 09:30:51 -0800235 service->Stop();
236}
237
Deyao Ren07595e12022-07-15 22:02:14 +0000238static std::string GetSecurityContext() {
239 char* ctx;
240 if (getcon(&ctx) == -1) {
241 ADD_FAILURE() << "Failed to call getcon : " << strerror(errno);
242 }
243 std::string result = std::string(ctx);
244 freecon(ctx);
245 return result;
246}
247
248void TestStartApexServices(const std::vector<std::string>& service_names,
249 const std::string& apex_name) {
250 for (auto const& svc : service_names) {
251 auto service = ServiceList::GetInstance().FindService(svc);
252 ASSERT_NE(nullptr, service);
253 ASSERT_RESULT_OK(service->Start());
254 ASSERT_TRUE(service->IsRunning());
255 LOG(INFO) << "Service " << svc << " is running";
256 if (!apex_name.empty()) {
257 service->set_filename("/apex/" + apex_name + "/init_test.rc");
258 } else {
259 service->set_filename("");
260 }
261 }
262 if (!apex_name.empty()) {
263 auto apex_services = ServiceList::GetInstance().FindServicesByApexName(apex_name);
264 EXPECT_EQ(service_names.size(), apex_services.size());
265 }
266}
267
268void TestStopApexServices(const std::vector<std::string>& service_names, bool expect_to_run) {
269 for (auto const& svc : service_names) {
270 auto service = ServiceList::GetInstance().FindService(svc);
271 ASSERT_NE(nullptr, service);
272 EXPECT_EQ(expect_to_run, service->IsRunning());
273 }
Deyao Ren238e9092022-07-21 23:05:13 +0000274}
275
276void TestRemoveApexService(const std::vector<std::string>& service_names, bool exist) {
277 for (auto const& svc : service_names) {
278 auto service = ServiceList::GetInstance().FindService(svc);
279 ASSERT_EQ(exist, service != nullptr);
280 }
Deyao Ren07595e12022-07-15 22:02:14 +0000281}
282
283void InitApexService(const std::string_view& init_template) {
284 std::string init_script = StringReplace(init_template, "$selabel",
285 GetSecurityContext(), true);
286
Deyao Ren238e9092022-07-21 23:05:13 +0000287 TestInitText(init_script, BuiltinFunctionMap(), {}, &ActionManager::GetInstance(),
Deyao Ren07595e12022-07-15 22:02:14 +0000288 &ServiceList::GetInstance());
289}
290
deyaoren@google.com909bc472022-09-07 22:25:44 +0000291void CleanupApexServices() {
292 std::vector<std::string> names;
293 for (const auto& s : ServiceList::GetInstance()) {
294 names.push_back(s->name());
295 }
296
297 for (const auto& name : names) {
298 auto s = ServiceList::GetInstance().FindService(name);
299 auto pid = s->pid();
300 ServiceList::GetInstance().RemoveService(*s);
301 if (pid > 0) {
302 kill(pid, SIGTERM);
303 kill(pid, SIGKILL);
304 }
305 }
306
307 ActionManager::GetInstance().RemoveActionIf([&](const std::unique_ptr<Action>& s) -> bool {
308 return true;
309 });
310}
311
Deyao Ren07595e12022-07-15 22:02:14 +0000312void TestApexServicesInit(const std::vector<std::string>& apex_services,
313 const std::vector<std::string>& other_apex_services,
314 const std::vector<std::string> non_apex_services) {
315 auto num_svc = apex_services.size() + other_apex_services.size() + non_apex_services.size();
Deyao Ren238e9092022-07-21 23:05:13 +0000316 ASSERT_EQ(num_svc, ServiceList::GetInstance().size());
Deyao Ren07595e12022-07-15 22:02:14 +0000317
318 TestStartApexServices(apex_services, "com.android.apex.test_service");
319 TestStartApexServices(other_apex_services, "com.android.other_apex.test_service");
320 TestStartApexServices(non_apex_services, /*apex_anme=*/ "");
321
322 StopServicesFromApex("com.android.apex.test_service");
323 TestStopApexServices(apex_services, /*expect_to_run=*/ false);
324 TestStopApexServices(other_apex_services, /*expect_to_run=*/ true);
325 TestStopApexServices(non_apex_services, /*expect_to_run=*/ true);
326
Deyao Ren238e9092022-07-21 23:05:13 +0000327 RemoveServiceAndActionFromApex("com.android.apex.test_service");
328 ASSERT_EQ(other_apex_services.size() + non_apex_services.size(),
329 ServiceList::GetInstance().size());
330
331 // TODO(b/244232142): Add test to check if actions are removed
332 TestRemoveApexService(apex_services, /*exist*/ false);
333 TestRemoveApexService(other_apex_services, /*exist*/ true);
334 TestRemoveApexService(non_apex_services, /*exist*/ true);
335
deyaoren@google.com909bc472022-09-07 22:25:44 +0000336 CleanupApexServices();
Deyao Ren07595e12022-07-15 22:02:14 +0000337}
338
339TEST(init, StopServiceByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900340 if (getuid() != 0) {
341 GTEST_SKIP() << "Must be run as root.";
342 return;
343 }
Deyao Ren07595e12022-07-15 22:02:14 +0000344 std::string_view script_template = R"init(
345service apex_test_service /system/bin/yes
346 user shell
347 group shell
348 seclabel $selabel
349)init";
350 InitApexService(script_template);
351 TestApexServicesInit({"apex_test_service"}, {}, {});
352}
353
354TEST(init, StopMultipleServicesByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900355 if (getuid() != 0) {
356 GTEST_SKIP() << "Must be run as root.";
357 return;
358 }
Deyao Ren07595e12022-07-15 22:02:14 +0000359 std::string_view script_template = R"init(
360service apex_test_service_multiple_a /system/bin/yes
361 user shell
362 group shell
363 seclabel $selabel
364service apex_test_service_multiple_b /system/bin/id
365 user shell
366 group shell
367 seclabel $selabel
368)init";
369 InitApexService(script_template);
370 TestApexServicesInit({"apex_test_service_multiple_a",
371 "apex_test_service_multiple_b"}, {}, {});
372}
373
374TEST(init, StopServicesFromMultipleApexes) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900375 if (getuid() != 0) {
376 GTEST_SKIP() << "Must be run as root.";
377 return;
378 }
Deyao Ren07595e12022-07-15 22:02:14 +0000379 std::string_view apex_script_template = R"init(
380service apex_test_service_multi_apex_a /system/bin/yes
381 user shell
382 group shell
383 seclabel $selabel
384service apex_test_service_multi_apex_b /system/bin/id
385 user shell
386 group shell
387 seclabel $selabel
388)init";
389 InitApexService(apex_script_template);
390
391 std::string_view other_apex_script_template = R"init(
392service apex_test_service_multi_apex_c /system/bin/yes
393 user shell
394 group shell
395 seclabel $selabel
396)init";
397 InitApexService(other_apex_script_template);
398
399 TestApexServicesInit({"apex_test_service_multi_apex_a",
400 "apex_test_service_multi_apex_b"}, {"apex_test_service_multi_apex_c"}, {});
401}
402
403TEST(init, StopServicesFromApexAndNonApex) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900404 if (getuid() != 0) {
405 GTEST_SKIP() << "Must be run as root.";
406 return;
407 }
Deyao Ren07595e12022-07-15 22:02:14 +0000408 std::string_view apex_script_template = R"init(
409service apex_test_service_apex_a /system/bin/yes
410 user shell
411 group shell
412 seclabel $selabel
413service apex_test_service_apex_b /system/bin/id
414 user shell
415 group shell
416 seclabel $selabel
417)init";
418 InitApexService(apex_script_template);
419
420 std::string_view non_apex_script_template = R"init(
421service apex_test_service_non_apex /system/bin/yes
422 user shell
423 group shell
424 seclabel $selabel
425)init";
426 InitApexService(non_apex_script_template);
427
428 TestApexServicesInit({"apex_test_service_apex_a",
429 "apex_test_service_apex_b"}, {}, {"apex_test_service_non_apex"});
430}
431
432TEST(init, StopServicesFromApexMixed) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900433 if (getuid() != 0) {
434 GTEST_SKIP() << "Must be run as root.";
435 return;
436 }
Deyao Ren07595e12022-07-15 22:02:14 +0000437 std::string_view script_template = R"init(
438service apex_test_service_mixed_a /system/bin/yes
439 user shell
440 group shell
441 seclabel $selabel
442)init";
443 InitApexService(script_template);
444
445 std::string_view other_apex_script_template = R"init(
446service apex_test_service_mixed_b /system/bin/yes
447 user shell
448 group shell
449 seclabel $selabel
450)init";
451 InitApexService(other_apex_script_template);
452
453 std::string_view non_apex_script_template = R"init(
454service apex_test_service_mixed_c /system/bin/yes
455 user shell
456 group shell
457 seclabel $selabel
458)init";
459 InitApexService(non_apex_script_template);
460
461 TestApexServicesInit({"apex_test_service_mixed_a"},
462 {"apex_test_service_mixed_b"}, {"apex_test_service_mixed_c"});
463}
464
Tom Cherryad54d092017-04-19 16:18:50 -0700465TEST(init, EventTriggerOrderMultipleFiles) {
466 // 6 total files, which should have their triggers executed in the following order:
467 // 1: start - original script parsed
468 // 2: first_import - immediately imported by first_script
469 // 3: dir_a - file named 'a.rc' in dir; dir is imported after first_import
470 // 4: a_import - file imported by dir_a
471 // 5: dir_b - file named 'b.rc' in dir
472 // 6: last_import - imported after dir is imported
473
474 TemporaryFile first_import;
475 ASSERT_TRUE(first_import.fd != -1);
476 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", first_import.fd));
477
478 TemporaryFile dir_a_import;
479 ASSERT_TRUE(dir_a_import.fd != -1);
480 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 4", dir_a_import.fd));
481
482 TemporaryFile last_import;
483 ASSERT_TRUE(last_import.fd != -1);
484 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 6", last_import.fd));
485
486 TemporaryDir dir;
487 // clang-format off
488 std::string dir_a_script = "import " + std::string(dir_a_import.path) + "\n"
489 "on boot\n"
490 "execute 3";
491 // clang-format on
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700492 // WriteFile() ensures the right mode is set
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900493 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/a.rc", dir_a_script));
Tom Cherryad54d092017-04-19 16:18:50 -0700494
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900495 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
Tom Cherryad54d092017-04-19 16:18:50 -0700496
497 // clang-format off
498 std::string start_script = "import " + std::string(first_import.path) + "\n"
499 "import " + std::string(dir.path) + "\n"
500 "import " + std::string(last_import.path) + "\n"
501 "on boot\n"
502 "execute 1";
503 // clang-format on
504 TemporaryFile start;
505 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
506
507 int num_executed = 0;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700508 auto execute_command = [&num_executed](const BuiltinArguments& args) {
Tom Cherryad54d092017-04-19 16:18:50 -0700509 EXPECT_EQ(2U, args.size());
510 EXPECT_EQ(++num_executed, std::stoi(args[1]));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700511 return Result<void>{};
Tom Cherryad54d092017-04-19 16:18:50 -0700512 };
513
Tom Cherryd52a5b32019-07-22 16:05:36 -0700514 BuiltinFunctionMap test_function_map = {
515 {"execute", {1, 1, {false, execute_command}}},
516 };
Tom Cherryad54d092017-04-19 16:18:50 -0700517
518 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
519 std::vector<ActionManagerCommand> commands{trigger_boot};
520
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900521 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800522 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900523 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
Tom Cherryad54d092017-04-19 16:18:50 -0700524
525 EXPECT_EQ(6, num_executed);
526}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700527
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900528BuiltinFunctionMap GetTestFunctionMapForLazyLoad(int& num_executed, ActionManager& action_manager) {
529 auto execute_command = [&num_executed](const BuiltinArguments& args) {
530 EXPECT_EQ(2U, args.size());
531 EXPECT_EQ(++num_executed, std::stoi(args[1]));
532 return Result<void>{};
533 };
534 auto load_command = [&action_manager](const BuiltinArguments& args) -> Result<void> {
535 EXPECT_EQ(2U, args.size());
536 Parser parser;
537 parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, nullptr));
538 if (!parser.ParseConfig(args[1])) {
539 return Error() << "Failed to load";
540 }
541 return Result<void>{};
542 };
543 auto trigger_command = [&action_manager](const BuiltinArguments& args) {
544 EXPECT_EQ(2U, args.size());
545 LOG(INFO) << "Queue event trigger: " << args[1];
546 action_manager.QueueEventTrigger(args[1]);
547 return Result<void>{};
548 };
549 BuiltinFunctionMap test_function_map = {
550 {"execute", {1, 1, {false, execute_command}}},
551 {"load", {1, 1, {false, load_command}}},
552 {"trigger", {1, 1, {false, trigger_command}}},
553 };
554 return test_function_map;
555}
556
557TEST(init, LazilyLoadedActionsCantBeTriggeredByTheSameTrigger) {
558 // "start" script loads "lazy" script. Even though "lazy" scripts
559 // defines "on boot" action, it's not executed by the current "boot"
560 // event because it's already processed.
561 TemporaryFile lazy;
562 ASSERT_TRUE(lazy.fd != -1);
563 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", lazy.fd));
564
565 TemporaryFile start;
566 // clang-format off
567 std::string start_script = "on boot\n"
568 "load " + std::string(lazy.path) + "\n"
569 "execute 1";
570 // clang-format on
571 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
572
573 int num_executed = 0;
574 ActionManager action_manager;
575 ServiceList service_list;
576 BuiltinFunctionMap test_function_map =
577 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
578
579 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
580 std::vector<ActionManagerCommand> commands{trigger_boot};
581 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
582
583 EXPECT_EQ(1, num_executed);
584}
585
586TEST(init, LazilyLoadedActionsCanBeTriggeredByTheNextTrigger) {
587 // "start" script loads "lazy" script and then triggers "next" event
588 // which executes "on next" action loaded by the previous command.
589 TemporaryFile lazy;
590 ASSERT_TRUE(lazy.fd != -1);
591 ASSERT_TRUE(android::base::WriteStringToFd("on next\nexecute 2", lazy.fd));
592
593 TemporaryFile start;
594 // clang-format off
595 std::string start_script = "on boot\n"
596 "load " + std::string(lazy.path) + "\n"
597 "execute 1\n"
598 "trigger next";
599 // clang-format on
600 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
601
602 int num_executed = 0;
603 ActionManager action_manager;
604 ServiceList service_list;
605 BuiltinFunctionMap test_function_map =
606 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
607
608 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
609 std::vector<ActionManagerCommand> commands{trigger_boot};
610 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
611
612 EXPECT_EQ(2, num_executed);
613}
614
Steven Morelande5349192023-04-24 23:54:59 +0000615TEST(init, RejectsNoUserStartingInV) {
616 std::string init_script =
617 R"init(
618service A something
619 class first
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
Steven Moreland5088e582024-05-29 00:03:19 +0000633 if (GetIntProperty("ro.vendor.api_level", 0) > 202404) {
Steven Morelande5349192023-04-24 23:54:59 +0000634 ASSERT_EQ(1u, parser.parse_error_count());
635 } else {
636 ASSERT_EQ(0u, parser.parse_error_count());
637 }
638}
639
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100640TEST(init, RejectsCriticalAndOneshotService) {
Tom Cherry0e40ba32020-07-09 08:47:24 -0700641 if (GetIntProperty("ro.product.first_api_level", 10000) < 30) {
642 GTEST_SKIP() << "Test only valid for devices launching with R or later";
643 }
644
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100645 std::string init_script =
646 R"init(
647service A something
648 class first
Steven Morelande5349192023-04-24 23:54:59 +0000649 user root
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100650 critical
651 oneshot
652)init";
653
654 TemporaryFile tf;
655 ASSERT_TRUE(tf.fd != -1);
656 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
657
658 ServiceList service_list;
659 Parser parser;
660 parser.AddSectionParser("service",
661 std::make_unique<ServiceParser>(&service_list, nullptr, std::nullopt));
662
663 ASSERT_TRUE(parser.ParseConfig(tf.path));
664 ASSERT_EQ(1u, parser.parse_error_count());
665}
666
Carlos Galo14471202022-12-07 23:39:05 +0000667TEST(init, MemLockLimit) {
668 // Test is enforced only for U+ devices
669 if (android::base::GetIntProperty("ro.vendor.api_level", 0) < __ANDROID_API_U__) {
670 GTEST_SKIP();
671 }
672
673 // Verify we are running memlock at, or under, 64KB
674 const unsigned long max_limit = 65536;
675 struct rlimit curr_limit;
676 ASSERT_EQ(getrlimit(RLIMIT_MEMLOCK, &curr_limit), 0);
677 ASSERT_LE(curr_limit.rlim_cur, max_limit);
678 ASSERT_LE(curr_limit.rlim_max, max_limit);
679}
680
Bart Van Assche468067a2023-02-14 09:52:31 -0800681void CloseAllFds() {
682 DIR* dir;
683 struct dirent* ent;
684 int fd;
685
686 if ((dir = opendir("/proc/self/fd"))) {
687 while ((ent = readdir(dir))) {
688 if (sscanf(ent->d_name, "%d", &fd) == 1) {
689 close(fd);
690 }
691 }
692 closedir(dir);
693 }
694}
695
Bart Van Assche947d75f2023-02-14 07:44:54 -0800696pid_t ForkExecvpAsync(const char* argv[]) {
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800697 pid_t pid = fork();
698 if (pid == 0) {
Bart Van Assche947d75f2023-02-14 07:44:54 -0800699 // Child process.
Bart Van Assche468067a2023-02-14 09:52:31 -0800700 CloseAllFds();
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800701
Bart Van Assche947d75f2023-02-14 07:44:54 -0800702 execvp(argv[0], const_cast<char**>(argv));
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800703 PLOG(ERROR) << "exec in ForkExecvpAsync init test";
704 _exit(EXIT_FAILURE);
705 }
Bart Van Assche947d75f2023-02-14 07:44:54 -0800706 // Parent process.
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800707 if (pid == -1) {
708 PLOG(ERROR) << "fork in ForkExecvpAsync init test";
709 return -1;
710 }
711 return pid;
712}
713
Bart Van Assche878560d2023-02-14 07:54:58 -0800714pid_t TracerPid(pid_t pid) {
715 static constexpr std::string_view prefix{"TracerPid:"};
716 std::ifstream is(StringPrintf("/proc/%d/status", pid));
717 std::string line;
718 while (std::getline(is, line)) {
719 if (line.find(prefix) == 0) {
720 return atoi(line.substr(prefix.length()).c_str());
721 }
722 }
723 return -1;
724}
725
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800726TEST(init, GentleKill) {
Daniel Rosenberg2f050862023-02-08 17:25:47 -0800727 if (getuid() != 0) {
728 GTEST_SKIP() << "Must be run as root.";
729 return;
730 }
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800731 std::string init_script = R"init(
732service test_gentle_kill /system/bin/sleep 1000
733 disabled
734 oneshot
735 gentle_kill
736 user root
737 group root
738 seclabel u:r:toolbox:s0
739)init";
740
741 ActionManager action_manager;
742 ServiceList service_list;
743 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
744 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
745
746 auto service = service_list.begin()->get();
747 ASSERT_NE(service, nullptr);
748 ASSERT_RESULT_OK(service->Start());
749 const pid_t pid = service->pid();
750 ASSERT_GT(pid, 0);
751 EXPECT_NE(getsid(pid), 0);
752
753 TemporaryFile logfile;
754 logfile.DoNotRemove();
755 ASSERT_TRUE(logfile.fd != -1);
756
Bart Van Assche947d75f2023-02-14 07:44:54 -0800757 std::string pid_str = std::to_string(pid);
758 const char* argv[] = {"/system/bin/strace", "-o", logfile.path, "-e", "signal", "-p",
759 pid_str.c_str(), nullptr};
760 pid_t strace_pid = ForkExecvpAsync(argv);
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800761
Bart Van Assche878560d2023-02-14 07:54:58 -0800762 // Give strace the chance to connect
763 while (TracerPid(pid) == 0) {
764 std::this_thread::sleep_for(10ms);
765 }
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800766 service->Stop();
767
768 int status;
769 waitpid(strace_pid, &status, 0);
770
771 std::string logs;
772 android::base::ReadFdToString(logfile.fd, &logs);
Bart Van Assche947d75f2023-02-14 07:44:54 -0800773 ASSERT_NE(logs.find("killed by SIGTERM"), std::string::npos);
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800774}
775
Nikita Ioffe9e4b1112020-12-11 17:59:38 +0000776class TestCaseLogger : public ::testing::EmptyTestEventListener {
777 void OnTestStart(const ::testing::TestInfo& test_info) override {
778#ifdef __ANDROID__
779 LOG(INFO) << "===== " << test_info.test_suite_name() << "::" << test_info.name() << " ("
780 << test_info.file() << ":" << test_info.line() << ")";
781#else
782 UNUSED(test_info);
783#endif
784 }
785};
786
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700787} // namespace init
788} // namespace android
Tom Cherrydcb3d152019-08-07 16:02:28 -0700789
790int SubcontextTestChildMain(int, char**);
791int FirmwareTestChildMain(int, char**);
792
793int main(int argc, char** argv) {
794 if (argc > 1 && !strcmp(argv[1], "subcontext")) {
795 return SubcontextTestChildMain(argc, argv);
796 }
797
798 if (argc > 1 && !strcmp(argv[1], "firmware")) {
799 return FirmwareTestChildMain(argc, argv);
800 }
801
802 testing::InitGoogleTest(&argc, argv);
Nikita Ioffe9e4b1112020-12-11 17:59:38 +0000803 testing::UnitTest::GetInstance()->listeners().Append(new android::init::TestCaseLogger());
Tom Cherrydcb3d152019-08-07 16:02:28 -0700804 return RUN_ALL_TESTS();
805}