1 /* 2 * Copyright (C) 2015 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 #ifndef _ADB_UTILS_H_ 18 #define _ADB_UTILS_H_ 19 20 #include <condition_variable> 21 #include <mutex> 22 #include <string> 23 #include <vector> 24 25 #include <android-base/macros.h> 26 27 int syntax_error(const char*, ...); 28 29 void close_stdin(); 30 31 bool getcwd(std::string* cwd); 32 bool directory_exists(const std::string& path); 33 34 // Return the user's home directory. 35 std::string adb_get_homedir_path(); 36 37 // Return the adb user directory. 38 std::string adb_get_android_dir_path(); 39 40 bool mkdirs(const std::string& path); 41 42 std::string escape_arg(const std::string& s); 43 44 std::string dump_hex(const void* ptr, size_t byte_count); 45 46 std::string perror_str(const char* msg); 47 48 bool set_file_block_mode(int fd, bool block); 49 50 extern int adb_close(int fd); 51 52 // Given forward/reverse targets, returns true if they look sane. If an error is found, fills 53 // |error| and returns false. 54 // Currently this only checks "tcp:" targets. Additional checking could be added for other targets 55 // if needed. 56 bool forward_targets_are_valid(const std::string& source, const std::string& dest, 57 std::string* error); 58 59 // A thread-safe blocking queue. 60 template <typename T> 61 class BlockingQueue { 62 std::mutex mutex; 63 std::condition_variable cv; 64 std::vector<T> queue; 65 66 public: Push(const T & t)67 void Push(const T& t) { 68 { 69 std::unique_lock<std::mutex> lock(mutex); 70 queue.push_back(t); 71 } 72 cv.notify_one(); 73 } 74 75 template <typename Fn> PopAll(Fn fn)76 void PopAll(Fn fn) { 77 std::vector<T> popped; 78 79 { 80 std::unique_lock<std::mutex> lock(mutex); 81 cv.wait(lock, [this]() { return !queue.empty(); }); 82 popped = std::move(queue); 83 queue.clear(); 84 } 85 86 for (const T& t : popped) { 87 fn(t); 88 } 89 } 90 }; 91 92 std::string GetLogFilePath(); 93 94 #endif 95