1 /*
2  * Copyright (C) 2016 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 "../dumpsys.h"
18 
19 #include <regex>
20 #include <vector>
21 
22 #include <gmock/gmock.h>
23 #include <gtest/gtest.h>
24 
25 #include <android-base/file.h>
26 #include <binder/Binder.h>
27 #include <binder/ProcessState.h>
28 #include <serviceutils/PriorityDumper.h>
29 #include <utils/String16.h>
30 #include <utils/String8.h>
31 #include <utils/Vector.h>
32 
33 using namespace android;
34 
35 using ::testing::_;
36 using ::testing::Action;
37 using ::testing::ActionInterface;
38 using ::testing::DoAll;
39 using ::testing::Eq;
40 using ::testing::HasSubstr;
41 using ::testing::MakeAction;
42 using ::testing::Mock;
43 using ::testing::Not;
44 using ::testing::Return;
45 using ::testing::StrEq;
46 using ::testing::Test;
47 using ::testing::WithArg;
48 using ::testing::internal::CaptureStderr;
49 using ::testing::internal::CaptureStdout;
50 using ::testing::internal::GetCapturedStderr;
51 using ::testing::internal::GetCapturedStdout;
52 
53 class ServiceManagerMock : public IServiceManager {
54   public:
55     MOCK_CONST_METHOD1(getService, sp<IBinder>(const String16&));
56     MOCK_CONST_METHOD1(checkService, sp<IBinder>(const String16&));
57     MOCK_METHOD4(addService, status_t(const String16&, const sp<IBinder>&, bool, int));
58     MOCK_METHOD1(listServices, Vector<String16>(int));
59     MOCK_METHOD1(waitForService, sp<IBinder>(const String16&));
60     MOCK_METHOD1(isDeclared, bool(const String16&));
61     MOCK_METHOD1(getDeclaredInstances, Vector<String16>(const String16&));
62     MOCK_METHOD1(updatableViaApex, std::optional<String16>(const String16&));
63     MOCK_METHOD1(getUpdatableNames, Vector<String16>(const String16&));
64     MOCK_METHOD1(getConnectionInfo, std::optional<ConnectionInfo>(const String16&));
65     MOCK_METHOD2(registerForNotifications, status_t(const String16&,
66                                              const sp<LocalRegistrationCallback>&));
67     MOCK_METHOD2(unregisterForNotifications, status_t(const String16&,
68                                              const sp<LocalRegistrationCallback>&));
69     MOCK_METHOD0(getServiceDebugInfo, std::vector<ServiceDebugInfo>());
70   protected:
71     MOCK_METHOD0(onAsBinder, IBinder*());
72 };
73 
74 class BinderMock : public BBinder {
75   public:
BinderMock()76     BinderMock() {
77     }
78 
79     MOCK_METHOD2(dump, status_t(int, const Vector<String16>&));
80 };
81 
82 // gmock black magic to provide a WithArg<0>(WriteOnFd(output)) matcher
83 typedef void WriteOnFdFunction(int);
84 
85 class WriteOnFdAction : public ActionInterface<WriteOnFdFunction> {
86   public:
WriteOnFdAction(const std::string & output)87     explicit WriteOnFdAction(const std::string& output) : output_(output) {
88     }
Perform(const ArgumentTuple & args)89     virtual Result Perform(const ArgumentTuple& args) {
90         int fd = ::testing::get<0>(args);
91         android::base::WriteStringToFd(output_, fd);
92     }
93 
94   private:
95     std::string output_;
96 };
97 
98 // Matcher used to emulate dump() by writing on its file descriptor.
WriteOnFd(const std::string & output)99 Action<WriteOnFdFunction> WriteOnFd(const std::string& output) {
100     return MakeAction(new WriteOnFdAction(output));
101 }
102 
103 // Matcher for args using Android's Vector<String16> format
104 // TODO: move it to some common testing library
105 MATCHER_P(AndroidElementsAre, expected, "") {
106     std::ostringstream errors;
107     if (arg.size() != expected.size()) {
108         errors << " sizes do not match (expected " << expected.size() << ", got " << arg.size()
109                << ")\n";
110     }
111     int i = 0;
112     std::ostringstream actual_stream, expected_stream;
113     for (const String16& actual : arg) {
114         std::string actual_str = String8(actual).c_str();
115         std::string expected_str = expected[i];
116         actual_stream << "'" << actual_str << "' ";
117         expected_stream << "'" << expected_str << "' ";
118         if (actual_str != expected_str) {
119             errors << " element mismatch at index " << i << "\n";
120         }
121         i++;
122     }
123 
124     if (!errors.str().empty()) {
125         errors << "\nExpected args: " << expected_stream.str()
126                << "\nActual args: " << actual_stream.str();
127         *result_listener << errors.str();
128         return false;
129     }
130     return true;
131 }
132 
133 // Custom action to sleep for timeout seconds
ACTION_P(Sleep,timeout)134 ACTION_P(Sleep, timeout) {
135     sleep(timeout);
136 }
137 
138 class DumpsysTest : public Test {
139   public:
DumpsysTest()140     DumpsysTest() : sm_(), dump_(&sm_), stdout_(), stderr_() {
141     }
142 
ExpectListServices(std::vector<std::string> services)143     void ExpectListServices(std::vector<std::string> services) {
144         Vector<String16> services16;
145         for (auto& service : services) {
146             services16.add(String16(service.c_str()));
147         }
148         EXPECT_CALL(sm_, listServices(IServiceManager::DUMP_FLAG_PRIORITY_ALL))
149             .WillRepeatedly(Return(services16));
150     }
151 
ExpectListServicesWithPriority(std::vector<std::string> services,int dumpFlags)152     void ExpectListServicesWithPriority(std::vector<std::string> services, int dumpFlags) {
153         Vector<String16> services16;
154         for (auto& service : services) {
155             services16.add(String16(service.c_str()));
156         }
157         EXPECT_CALL(sm_, listServices(dumpFlags)).WillRepeatedly(Return(services16));
158     }
159 
ExpectCheckService(const char * name,bool running=true)160     sp<BinderMock> ExpectCheckService(const char* name, bool running = true) {
161         sp<BinderMock> binder_mock;
162         if (running) {
163             binder_mock = new BinderMock;
164         }
165         EXPECT_CALL(sm_, checkService(String16(name))).WillRepeatedly(Return(binder_mock));
166         return binder_mock;
167     }
168 
ExpectDump(const char * name,const std::string & output)169     void ExpectDump(const char* name, const std::string& output) {
170         sp<BinderMock> binder_mock = ExpectCheckService(name);
171         EXPECT_CALL(*binder_mock, dump(_, _))
172             .WillRepeatedly(DoAll(WithArg<0>(WriteOnFd(output)), Return(0)));
173     }
174 
ExpectDumpWithArgs(const char * name,std::vector<std::string> args,const std::string & output)175     void ExpectDumpWithArgs(const char* name, std::vector<std::string> args,
176                             const std::string& output) {
177         sp<BinderMock> binder_mock = ExpectCheckService(name);
178         EXPECT_CALL(*binder_mock, dump(_, AndroidElementsAre(args)))
179             .WillRepeatedly(DoAll(WithArg<0>(WriteOnFd(output)), Return(0)));
180     }
181 
ExpectDumpAndHang(const char * name,int timeout_s,const std::string & output)182     sp<BinderMock> ExpectDumpAndHang(const char* name, int timeout_s, const std::string& output) {
183         sp<BinderMock> binder_mock = ExpectCheckService(name);
184         EXPECT_CALL(*binder_mock, dump(_, _))
185             .WillRepeatedly(DoAll(Sleep(timeout_s), WithArg<0>(WriteOnFd(output)), Return(0)));
186         return binder_mock;
187     }
188 
CallMain(const std::vector<std::string> & args)189     void CallMain(const std::vector<std::string>& args) {
190         const char* argv[1024] = {"/some/virtual/dir/dumpsys"};
191         int argc = (int)args.size() + 1;
192         int i = 1;
193         for (const std::string& arg : args) {
194             argv[i++] = arg.c_str();
195         }
196         CaptureStdout();
197         CaptureStderr();
198         int status = dump_.main(argc, const_cast<char**>(argv));
199         stdout_ = GetCapturedStdout();
200         stderr_ = GetCapturedStderr();
201         EXPECT_THAT(status, Eq(0));
202     }
203 
CallSingleService(const String16 & serviceName,Vector<String16> & args,int priorityFlags,bool supportsProto,std::chrono::duration<double> & elapsedDuration,size_t & bytesWritten)204     void CallSingleService(const String16& serviceName, Vector<String16>& args, int priorityFlags,
205                            bool supportsProto, std::chrono::duration<double>& elapsedDuration,
206                            size_t& bytesWritten) {
207         CaptureStdout();
208         CaptureStderr();
209         dump_.setServiceArgs(args, supportsProto, priorityFlags);
210         status_t status = dump_.startDumpThread(Dumpsys::TYPE_DUMP, serviceName, args);
211         EXPECT_THAT(status, Eq(0));
212         status = dump_.writeDump(STDOUT_FILENO, serviceName, std::chrono::milliseconds(500), false,
213                                  elapsedDuration, bytesWritten);
214         EXPECT_THAT(status, Eq(0));
215         dump_.stopDumpThread(/* dumpCompleted = */ true);
216         stdout_ = GetCapturedStdout();
217         stderr_ = GetCapturedStderr();
218     }
219 
AssertRunningServices(const std::vector<std::string> & services)220     void AssertRunningServices(const std::vector<std::string>& services) {
221         std::string expected = "Currently running services:\n";
222         for (const std::string& service : services) {
223             expected.append("  ").append(service).append("\n");
224         }
225         EXPECT_THAT(stdout_, HasSubstr(expected));
226     }
227 
AssertOutput(const std::string & expected)228     void AssertOutput(const std::string& expected) {
229         EXPECT_THAT(stdout_, StrEq(expected));
230     }
231 
AssertOutputContains(const std::string & expected)232     void AssertOutputContains(const std::string& expected) {
233         EXPECT_THAT(stdout_, HasSubstr(expected));
234     }
235 
AssertOutputFormat(const std::string format)236     void AssertOutputFormat(const std::string format) {
237         EXPECT_THAT(stdout_, testing::MatchesRegex(format));
238     }
239 
AssertDumped(const std::string & service,const std::string & dump)240     void AssertDumped(const std::string& service, const std::string& dump) {
241         EXPECT_THAT(stdout_, HasSubstr("DUMP OF SERVICE " + service + ":\n" + dump));
242         EXPECT_THAT(stdout_, HasSubstr("was the duration of dumpsys " + service + ", ending at: "));
243     }
244 
AssertDumpedWithPriority(const std::string & service,const std::string & dump,const char16_t * priorityType)245     void AssertDumpedWithPriority(const std::string& service, const std::string& dump,
246                                   const char16_t* priorityType) {
247         std::string priority = String8(priorityType).c_str();
248         EXPECT_THAT(stdout_,
249                     HasSubstr("DUMP OF SERVICE " + priority + " " + service + ":\n" + dump));
250         EXPECT_THAT(stdout_, HasSubstr("was the duration of dumpsys " + service + ", ending at: "));
251     }
252 
AssertNotDumped(const std::string & dump)253     void AssertNotDumped(const std::string& dump) {
254         EXPECT_THAT(stdout_, Not(HasSubstr(dump)));
255     }
256 
AssertStopped(const std::string & service)257     void AssertStopped(const std::string& service) {
258         EXPECT_THAT(stderr_, HasSubstr("Can't find service: " + service + "\n"));
259     }
260 
261     ServiceManagerMock sm_;
262     Dumpsys dump_;
263 
264   private:
265     std::string stdout_, stderr_;
266 };
267 
268 // Tests 'dumpsys -l' when all services are running
TEST_F(DumpsysTest,ListAllServices)269 TEST_F(DumpsysTest, ListAllServices) {
270     ExpectListServices({"Locksmith", "Valet"});
271     ExpectCheckService("Locksmith");
272     ExpectCheckService("Valet");
273 
274     CallMain({"-l"});
275 
276     AssertRunningServices({"Locksmith", "Valet"});
277 }
278 
TEST_F(DumpsysTest,ListServicesOneRegistered)279 TEST_F(DumpsysTest, ListServicesOneRegistered) {
280     ExpectListServices({"Locksmith"});
281     ExpectCheckService("Locksmith");
282 
283     CallMain({"-l"});
284 
285     AssertRunningServices({"Locksmith"});
286 }
287 
TEST_F(DumpsysTest,ListServicesEmpty)288 TEST_F(DumpsysTest, ListServicesEmpty) {
289     CallMain({"-l"});
290 
291     AssertRunningServices({});
292 }
293 
294 // Tests 'dumpsys -l' when a service is not running
TEST_F(DumpsysTest,ListRunningServices)295 TEST_F(DumpsysTest, ListRunningServices) {
296     ExpectListServices({"Locksmith", "Valet"});
297     ExpectCheckService("Locksmith");
298     ExpectCheckService("Valet", false);
299 
300     CallMain({"-l"});
301 
302     AssertRunningServices({"Locksmith"});
303     AssertNotDumped({"Valet"});
304 }
305 
306 // Tests 'dumpsys -l --priority HIGH'
TEST_F(DumpsysTest,ListAllServicesWithPriority)307 TEST_F(DumpsysTest, ListAllServicesWithPriority) {
308     ExpectListServicesWithPriority({"Locksmith", "Valet"}, IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
309     ExpectCheckService("Locksmith");
310     ExpectCheckService("Valet");
311 
312     CallMain({"-l", "--priority", "HIGH"});
313 
314     AssertRunningServices({"Locksmith", "Valet"});
315 }
316 
317 // Tests 'dumpsys -l --priority HIGH' with and empty list
TEST_F(DumpsysTest,ListEmptyServicesWithPriority)318 TEST_F(DumpsysTest, ListEmptyServicesWithPriority) {
319     ExpectListServicesWithPriority({}, IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
320 
321     CallMain({"-l", "--priority", "HIGH"});
322 
323     AssertRunningServices({});
324 }
325 
326 // Tests 'dumpsys -l --proto'
TEST_F(DumpsysTest,ListAllServicesWithProto)327 TEST_F(DumpsysTest, ListAllServicesWithProto) {
328     ExpectListServicesWithPriority({"Locksmith", "Valet", "Car"},
329                                    IServiceManager::DUMP_FLAG_PRIORITY_ALL);
330     ExpectListServicesWithPriority({"Valet", "Car"}, IServiceManager::DUMP_FLAG_PROTO);
331     ExpectCheckService("Car");
332     ExpectCheckService("Valet");
333 
334     CallMain({"-l", "--proto"});
335 
336     AssertRunningServices({"Car", "Valet"});
337 }
338 
339 // Tests 'dumpsys service_name' on a service is running
TEST_F(DumpsysTest,DumpRunningService)340 TEST_F(DumpsysTest, DumpRunningService) {
341     ExpectDump("Valet", "Here's your car");
342 
343     CallMain({"Valet"});
344 
345     AssertOutput("Here's your car");
346 }
347 
348 // Tests 'dumpsys -t 1 service_name' on a service that times out after 2s
TEST_F(DumpsysTest,DumpRunningServiceTimeoutInSec)349 TEST_F(DumpsysTest, DumpRunningServiceTimeoutInSec) {
350     sp<BinderMock> binder_mock = ExpectDumpAndHang("Valet", 2, "Here's your car");
351 
352     CallMain({"-t", "1", "Valet"});
353 
354     AssertOutputContains("SERVICE 'Valet' DUMP TIMEOUT (1000ms) EXPIRED");
355     AssertNotDumped("Here's your car");
356 
357     // TODO(b/65056227): BinderMock is not destructed because thread is detached on dumpsys.cpp
358     Mock::AllowLeak(binder_mock.get());
359 }
360 
361 // Tests 'dumpsys -T 500 service_name' on a service that times out after 2s
TEST_F(DumpsysTest,DumpRunningServiceTimeoutInMs)362 TEST_F(DumpsysTest, DumpRunningServiceTimeoutInMs) {
363     sp<BinderMock> binder_mock = ExpectDumpAndHang("Valet", 2, "Here's your car");
364 
365     CallMain({"-T", "500", "Valet"});
366 
367     AssertOutputContains("SERVICE 'Valet' DUMP TIMEOUT (500ms) EXPIRED");
368     AssertNotDumped("Here's your car");
369 
370     // TODO(b/65056227): BinderMock is not destructed because thread is detached on dumpsys.cpp
371     Mock::AllowLeak(binder_mock.get());
372 }
373 
374 // Tests 'dumpsys service_name Y U NO HAVE ARGS' on a service that is running
TEST_F(DumpsysTest,DumpWithArgsRunningService)375 TEST_F(DumpsysTest, DumpWithArgsRunningService) {
376     ExpectDumpWithArgs("SERVICE", {"Y", "U", "NO", "HANDLE", "ARGS"}, "I DO!");
377 
378     CallMain({"SERVICE", "Y", "U", "NO", "HANDLE", "ARGS"});
379 
380     AssertOutput("I DO!");
381 }
382 
383 // Tests dumpsys passes the -a flag when called on all services
TEST_F(DumpsysTest,PassAllFlagsToServices)384 TEST_F(DumpsysTest, PassAllFlagsToServices) {
385     ExpectListServices({"Locksmith", "Valet"});
386     ExpectCheckService("Locksmith");
387     ExpectCheckService("Valet");
388     ExpectDumpWithArgs("Locksmith", {"-a"}, "dumped1");
389     ExpectDumpWithArgs("Valet", {"-a"}, "dumped2");
390 
391     CallMain({"-T", "500"});
392 
393     AssertDumped("Locksmith", "dumped1");
394     AssertDumped("Valet", "dumped2");
395 }
396 
397 // Tests dumpsys passes the -a flag when called on NORMAL priority services
TEST_F(DumpsysTest,PassAllFlagsToNormalServices)398 TEST_F(DumpsysTest, PassAllFlagsToNormalServices) {
399     ExpectListServicesWithPriority({"Locksmith", "Valet"},
400                                    IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
401     ExpectCheckService("Locksmith");
402     ExpectCheckService("Valet");
403     ExpectDumpWithArgs("Locksmith", {"--dump-priority", "NORMAL", "-a"}, "dump1");
404     ExpectDumpWithArgs("Valet", {"--dump-priority", "NORMAL", "-a"}, "dump2");
405 
406     CallMain({"--priority", "NORMAL"});
407 
408     AssertDumped("Locksmith", "dump1");
409     AssertDumped("Valet", "dump2");
410 }
411 
412 // Tests dumpsys passes only priority flags when called on CRITICAL priority services
TEST_F(DumpsysTest,PassPriorityFlagsToCriticalServices)413 TEST_F(DumpsysTest, PassPriorityFlagsToCriticalServices) {
414     ExpectListServicesWithPriority({"Locksmith", "Valet"},
415                                    IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
416     ExpectCheckService("Locksmith");
417     ExpectCheckService("Valet");
418     ExpectDumpWithArgs("Locksmith", {"--dump-priority", "CRITICAL"}, "dump1");
419     ExpectDumpWithArgs("Valet", {"--dump-priority", "CRITICAL"}, "dump2");
420 
421     CallMain({"--priority", "CRITICAL"});
422 
423     AssertDumpedWithPriority("Locksmith", "dump1", PriorityDumper::PRIORITY_ARG_CRITICAL);
424     AssertDumpedWithPriority("Valet", "dump2", PriorityDumper::PRIORITY_ARG_CRITICAL);
425 }
426 
427 // Tests dumpsys passes only priority flags when called on HIGH priority services
TEST_F(DumpsysTest,PassPriorityFlagsToHighServices)428 TEST_F(DumpsysTest, PassPriorityFlagsToHighServices) {
429     ExpectListServicesWithPriority({"Locksmith", "Valet"},
430                                    IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
431     ExpectCheckService("Locksmith");
432     ExpectCheckService("Valet");
433     ExpectDumpWithArgs("Locksmith", {"--dump-priority", "HIGH"}, "dump1");
434     ExpectDumpWithArgs("Valet", {"--dump-priority", "HIGH"}, "dump2");
435 
436     CallMain({"--priority", "HIGH"});
437 
438     AssertDumpedWithPriority("Locksmith", "dump1", PriorityDumper::PRIORITY_ARG_HIGH);
439     AssertDumpedWithPriority("Valet", "dump2", PriorityDumper::PRIORITY_ARG_HIGH);
440 }
441 
442 // Tests 'dumpsys' with no arguments
TEST_F(DumpsysTest,DumpMultipleServices)443 TEST_F(DumpsysTest, DumpMultipleServices) {
444     ExpectListServices({"running1", "stopped2", "running3"});
445     ExpectDump("running1", "dump1");
446     ExpectCheckService("stopped2", false);
447     ExpectDump("running3", "dump3");
448 
449     CallMain({});
450 
451     AssertRunningServices({"running1", "running3"});
452     AssertDumped("running1", "dump1");
453     AssertStopped("stopped2");
454     AssertDumped("running3", "dump3");
455 }
456 
457 // Tests 'dumpsys --skip skipped3 skipped5', which should skip these services
TEST_F(DumpsysTest,DumpWithSkip)458 TEST_F(DumpsysTest, DumpWithSkip) {
459     ExpectListServices({"running1", "stopped2", "skipped3", "running4", "skipped5"});
460     ExpectDump("running1", "dump1");
461     ExpectCheckService("stopped2", false);
462     ExpectDump("skipped3", "dump3");
463     ExpectDump("running4", "dump4");
464     ExpectDump("skipped5", "dump5");
465 
466     CallMain({"--skip", "skipped3", "skipped5"});
467 
468     AssertRunningServices({"running1", "running4", "skipped3 (skipped)", "skipped5 (skipped)"});
469     AssertDumped("running1", "dump1");
470     AssertDumped("running4", "dump4");
471     AssertStopped("stopped2");
472     AssertNotDumped("dump3");
473     AssertNotDumped("dump5");
474 }
475 
476 // Tests 'dumpsys --skip skipped3 skipped5 --priority CRITICAL', which should skip these services
TEST_F(DumpsysTest,DumpWithSkipAndPriority)477 TEST_F(DumpsysTest, DumpWithSkipAndPriority) {
478     ExpectListServicesWithPriority({"running1", "stopped2", "skipped3", "running4", "skipped5"},
479                                    IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
480     ExpectDump("running1", "dump1");
481     ExpectCheckService("stopped2", false);
482     ExpectDump("skipped3", "dump3");
483     ExpectDump("running4", "dump4");
484     ExpectDump("skipped5", "dump5");
485 
486     CallMain({"--priority", "CRITICAL", "--skip", "skipped3", "skipped5"});
487 
488     AssertRunningServices({"running1", "running4", "skipped3 (skipped)", "skipped5 (skipped)"});
489     AssertDumpedWithPriority("running1", "dump1", PriorityDumper::PRIORITY_ARG_CRITICAL);
490     AssertDumpedWithPriority("running4", "dump4", PriorityDumper::PRIORITY_ARG_CRITICAL);
491     AssertStopped("stopped2");
492     AssertNotDumped("dump3");
493     AssertNotDumped("dump5");
494 }
495 
496 // Tests 'dumpsys --priority CRITICAL'
TEST_F(DumpsysTest,DumpWithPriorityCritical)497 TEST_F(DumpsysTest, DumpWithPriorityCritical) {
498     ExpectListServicesWithPriority({"runningcritical1", "runningcritical2"},
499                                    IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL);
500     ExpectDump("runningcritical1", "dump1");
501     ExpectDump("runningcritical2", "dump2");
502 
503     CallMain({"--priority", "CRITICAL"});
504 
505     AssertRunningServices({"runningcritical1", "runningcritical2"});
506     AssertDumpedWithPriority("runningcritical1", "dump1", PriorityDumper::PRIORITY_ARG_CRITICAL);
507     AssertDumpedWithPriority("runningcritical2", "dump2", PriorityDumper::PRIORITY_ARG_CRITICAL);
508 }
509 
510 // Tests 'dumpsys --priority HIGH'
TEST_F(DumpsysTest,DumpWithPriorityHigh)511 TEST_F(DumpsysTest, DumpWithPriorityHigh) {
512     ExpectListServicesWithPriority({"runninghigh1", "runninghigh2"},
513                                    IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
514     ExpectDump("runninghigh1", "dump1");
515     ExpectDump("runninghigh2", "dump2");
516 
517     CallMain({"--priority", "HIGH"});
518 
519     AssertRunningServices({"runninghigh1", "runninghigh2"});
520     AssertDumpedWithPriority("runninghigh1", "dump1", PriorityDumper::PRIORITY_ARG_HIGH);
521     AssertDumpedWithPriority("runninghigh2", "dump2", PriorityDumper::PRIORITY_ARG_HIGH);
522 }
523 
524 // Tests 'dumpsys --priority NORMAL'
TEST_F(DumpsysTest,DumpWithPriorityNormal)525 TEST_F(DumpsysTest, DumpWithPriorityNormal) {
526     ExpectListServicesWithPriority({"runningnormal1", "runningnormal2"},
527                                    IServiceManager::DUMP_FLAG_PRIORITY_NORMAL);
528     ExpectDump("runningnormal1", "dump1");
529     ExpectDump("runningnormal2", "dump2");
530 
531     CallMain({"--priority", "NORMAL"});
532 
533     AssertRunningServices({"runningnormal1", "runningnormal2"});
534     AssertDumped("runningnormal1", "dump1");
535     AssertDumped("runningnormal2", "dump2");
536 }
537 
538 // Tests 'dumpsys --proto'
TEST_F(DumpsysTest,DumpWithProto)539 TEST_F(DumpsysTest, DumpWithProto) {
540     ExpectListServicesWithPriority({"run8", "run1", "run2", "run5"},
541                                    IServiceManager::DUMP_FLAG_PRIORITY_ALL);
542     ExpectListServicesWithPriority({"run3", "run2", "run4", "run8"},
543                                    IServiceManager::DUMP_FLAG_PROTO);
544     ExpectDump("run2", "dump1");
545     ExpectDump("run8", "dump2");
546 
547     CallMain({"--proto"});
548 
549     AssertRunningServices({"run2", "run8"});
550     AssertDumped("run2", "dump1");
551     AssertDumped("run8", "dump2");
552 }
553 
554 // Tests 'dumpsys --priority HIGH --proto'
TEST_F(DumpsysTest,DumpWithPriorityHighAndProto)555 TEST_F(DumpsysTest, DumpWithPriorityHighAndProto) {
556     ExpectListServicesWithPriority({"runninghigh1", "runninghigh2"},
557                                    IServiceManager::DUMP_FLAG_PRIORITY_HIGH);
558     ExpectListServicesWithPriority({"runninghigh1", "runninghigh2", "runninghigh3"},
559                                    IServiceManager::DUMP_FLAG_PROTO);
560 
561     ExpectDump("runninghigh1", "dump1");
562     ExpectDump("runninghigh2", "dump2");
563 
564     CallMain({"--priority", "HIGH", "--proto"});
565 
566     AssertRunningServices({"runninghigh1", "runninghigh2"});
567     AssertDumpedWithPriority("runninghigh1", "dump1", PriorityDumper::PRIORITY_ARG_HIGH);
568     AssertDumpedWithPriority("runninghigh2", "dump2", PriorityDumper::PRIORITY_ARG_HIGH);
569 }
570 
571 // Tests 'dumpsys --pid'
TEST_F(DumpsysTest,ListAllServicesWithPid)572 TEST_F(DumpsysTest, ListAllServicesWithPid) {
573     ExpectListServices({"Locksmith", "Valet"});
574     ExpectCheckService("Locksmith");
575     ExpectCheckService("Valet");
576 
577     CallMain({"--pid"});
578 
579     AssertRunningServices({"Locksmith", "Valet"});
580     AssertOutputContains(std::to_string(getpid()));
581 }
582 
583 // Tests 'dumpsys --pid service_name'
TEST_F(DumpsysTest,ListServiceWithPid)584 TEST_F(DumpsysTest, ListServiceWithPid) {
585     ExpectCheckService("Locksmith");
586 
587     CallMain({"--pid", "Locksmith"});
588 
589     AssertOutput(std::to_string(getpid()) + "\n");
590 }
591 
592 // Tests 'dumpsys --stability'
TEST_F(DumpsysTest,ListAllServicesWithStability)593 TEST_F(DumpsysTest, ListAllServicesWithStability) {
594     ExpectListServices({"Locksmith", "Valet"});
595     ExpectCheckService("Locksmith");
596     ExpectCheckService("Valet");
597 
598     CallMain({"--stability"});
599 
600     AssertRunningServices({"Locksmith", "Valet"});
601     AssertOutputContains("stability");
602 }
603 
604 // Tests 'dumpsys --stability service_name'
TEST_F(DumpsysTest,ListServiceWithStability)605 TEST_F(DumpsysTest, ListServiceWithStability) {
606     ExpectCheckService("Locksmith");
607 
608     CallMain({"--stability", "Locksmith"});
609 
610     AssertOutputContains("stability");
611 }
612 
613 // Tests 'dumpsys --thread'
TEST_F(DumpsysTest,ListAllServicesWithThread)614 TEST_F(DumpsysTest, ListAllServicesWithThread) {
615     ExpectListServices({"Locksmith", "Valet"});
616     ExpectCheckService("Locksmith");
617     ExpectCheckService("Valet");
618 
619     CallMain({"--thread"});
620 
621     AssertRunningServices({"Locksmith", "Valet"});
622 
623     const std::string format("(.|\n)*((Threads in use: [0-9]+/[0-9]+)?\n-(.|\n)*){2}");
624     AssertOutputFormat(format);
625 }
626 
627 // Tests 'dumpsys --thread service_name'
TEST_F(DumpsysTest,ListServiceWithThread)628 TEST_F(DumpsysTest, ListServiceWithThread) {
629     ExpectCheckService("Locksmith");
630 
631     CallMain({"--thread", "Locksmith"});
632     // returns an empty string without root enabled
633     const std::string format("(^$|Threads in use: [0-9]/[0-9]+\n)");
634     AssertOutputFormat(format);
635 }
636 
637 // Tests 'dumpsys --clients'
TEST_F(DumpsysTest,ListAllServicesWithClients)638 TEST_F(DumpsysTest, ListAllServicesWithClients) {
639     ExpectListServices({"Locksmith", "Valet"});
640     ExpectCheckService("Locksmith");
641     ExpectCheckService("Valet");
642 
643     CallMain({"--clients"});
644 
645     AssertRunningServices({"Locksmith", "Valet"});
646 
647     const std::string format("(.|\n)*((Client PIDs are not available for local binders.)(.|\n)*){2}");
648     AssertOutputFormat(format);
649 }
650 
651 // Tests 'dumpsys --clients service_name'
TEST_F(DumpsysTest,ListServiceWithClients)652 TEST_F(DumpsysTest, ListServiceWithClients) {
653     ExpectCheckService("Locksmith");
654 
655     CallMain({"--clients", "Locksmith"});
656 
657     const std::string format("Client PIDs are not available for local binders.\n");
658     AssertOutputFormat(format);
659 }
660 // Tests 'dumpsys --thread --stability'
TEST_F(DumpsysTest,ListAllServicesWithMultipleOptions)661 TEST_F(DumpsysTest, ListAllServicesWithMultipleOptions) {
662     ExpectListServices({"Locksmith", "Valet"});
663     ExpectCheckService("Locksmith");
664     ExpectCheckService("Valet");
665 
666     CallMain({"--pid", "--stability"});
667     AssertRunningServices({"Locksmith", "Valet"});
668 
669     AssertOutputContains(std::to_string(getpid()));
670     AssertOutputContains("stability");
671 }
672 
673 // Tests 'dumpsys --pid --stability service_name'
TEST_F(DumpsysTest,ListServiceWithMultipleOptions)674 TEST_F(DumpsysTest, ListServiceWithMultipleOptions) {
675     ExpectCheckService("Locksmith");
676     CallMain({"--pid", "--stability", "Locksmith"});
677 
678     AssertOutputContains(std::to_string(getpid()));
679     AssertOutputContains("stability");
680 }
681 
TEST_F(DumpsysTest,GetBytesWritten)682 TEST_F(DumpsysTest, GetBytesWritten) {
683     const char* serviceName = "service2";
684     const char* dumpContents = "dump1";
685     ExpectDump(serviceName, dumpContents);
686 
687     String16 service(serviceName);
688     Vector<String16> args;
689     std::chrono::duration<double> elapsedDuration;
690     size_t bytesWritten;
691 
692     CallSingleService(service, args, IServiceManager::DUMP_FLAG_PRIORITY_ALL,
693                       /* as_proto = */ false, elapsedDuration, bytesWritten);
694 
695     AssertOutput(dumpContents);
696     EXPECT_THAT(bytesWritten, Eq(strlen(dumpContents)));
697 }
698 
TEST_F(DumpsysTest,WriteDumpWithoutThreadStart)699 TEST_F(DumpsysTest, WriteDumpWithoutThreadStart) {
700     std::chrono::duration<double> elapsedDuration;
701     size_t bytesWritten;
702     status_t status =
703         dump_.writeDump(STDOUT_FILENO, String16("service"), std::chrono::milliseconds(500),
704                         /* as_proto = */ false, elapsedDuration, bytesWritten);
705     EXPECT_THAT(status, Eq(INVALID_OPERATION));
706 }
707 
main(int argc,char ** argv)708 int main(int argc, char** argv) {
709     ::testing::InitGoogleTest(&argc, argv);
710 
711     // start a binder thread pool for testing --thread option
712     android::ProcessState::self()->setThreadPoolMaxThreadCount(8);
713     ProcessState::self()->startThreadPool();
714 
715     return RUN_ALL_TESTS();
716 }
717