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