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