1 /*
2  * Copyright (C) 2019 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 <android-base/logging.h>
18 #include <android-base/properties.h>
19 #include <android/lpdump/ILpdump.h>
20 #include <binder/IServiceManager.h>
21 #include <iostream>
22 #include <string>
23 #include <vector>
24 
25 using namespace android;
26 using namespace std::chrono_literals;
27 using ::android::lpdump::ILpdump;
28 
29 int Run(ILpdump* service, const std::vector<std::string>& args) {
30     std::string output;
31     binder::Status status = service->run(args, &output);
32     if (status.isOk()) {
33         std::cout << output;
34         return 0;
35     }
36     std::cerr << status.exceptionMessage();
37     if (status.serviceSpecificErrorCode() != 0) {
38         return status.serviceSpecificErrorCode();
39     }
40     return -status.exceptionCode();
41 }
42 
43 std::vector<std::string> GetArgVector(int argc, char* argv[]) {
44     std::vector<std::string> args;
45     args.reserve(argc);
46     for (int i = 0; i < argc; ++i) {
47         args.push_back(argv[i]);
48     }
49     return args;
50 }
51 
52 class LpdumpService {
53 public:
54     LpdumpService() {
55         base::SetProperty("sys.lpdumpd", "start");
56         status_t status = getService(String16("lpdump_service"), &service_);
57         int wait_counter = 0;
58         while (status != OK && wait_counter++ < 3) {
59             sleep(1);
60             status = getService(String16("lpdump"), &service_);
61         }
62         if (status != OK || service_ == nullptr) {
63             std::cerr << "Cannot get lpdump service: " << strerror(-status) << std::endl;
64             LOG(ERROR) << "Cannot get lpdump service: " << strerror(-status);
65         }
66     }
67     ~LpdumpService() {
68         base::SetProperty("sys.lpdumpd", "stop");
69     }
70     sp<ILpdump> get() { return service_; }
71 private:
72     sp<ILpdump> service_;
73 };
74 
75 int main(int argc, char* argv[]) {
76     LpdumpService wrapper;
77     sp<ILpdump> service = wrapper.get();
78     if (service == nullptr) {
79         return 1;
80     }
81     int ret = Run(service.get(), GetArgVector(argc, argv));
82     base::SetProperty("sys.lpdumpd", "stop");
83     return ret;
84 }
85