Ken Chen | 76ee610 | 2022-01-15 01:11:53 +0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2022 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 "nettestutils/DumpService.h" |
| 18 | |
| 19 | #include <android-base/file.h> |
| 20 | |
| 21 | #include <sstream> |
| 22 | #include <thread> |
| 23 | |
| 24 | android::status_t dumpService(const android::sp<android::IBinder>& binder, |
| 25 | const std::vector<std::string>& args, |
| 26 | std::vector<std::string>& outputLines) { |
| 27 | if (!outputLines.empty()) return -EUCLEAN; |
| 28 | |
| 29 | android::base::unique_fd localFd, remoteFd; |
| 30 | if (!Pipe(&localFd, &remoteFd)) return -errno; |
| 31 | |
| 32 | android::Vector<android::String16> str16Args; |
| 33 | for (const auto& arg : args) { |
| 34 | str16Args.push(android::String16(arg.c_str())); |
| 35 | } |
| 36 | android::status_t ret; |
| 37 | // dump() blocks until another thread has consumed all its output. |
| 38 | std::thread dumpThread = |
| 39 | std::thread([&ret, binder, remoteFd{std::move(remoteFd)}, str16Args]() { |
| 40 | ret = binder->dump(remoteFd, str16Args); |
| 41 | }); |
| 42 | |
| 43 | std::string dumpContent; |
| 44 | if (!android::base::ReadFdToString(localFd.get(), &dumpContent)) { |
| 45 | return -errno; |
| 46 | } |
| 47 | dumpThread.join(); |
| 48 | if (ret != android::OK) return ret; |
| 49 | |
| 50 | std::stringstream dumpStream(std::move(dumpContent)); |
| 51 | std::string line; |
| 52 | while (std::getline(dumpStream, line)) { |
| 53 | outputLines.push_back(line); |
| 54 | } |
| 55 | |
| 56 | return android::OK; |
| 57 | } |