blob: 0645122b78442c183f15c8252a7222af0e7e2ad7 [file] [log] [blame]
Elliott Hughes58305772015-04-17 13:57:15 -07001/*
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
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG ADB
Elliott Hughese67f1f82015-04-30 17:32:03 -070018
Elliott Hughes58305772015-04-17 13:57:15 -070019#include "adb_utils.h"
20
Spencer Low22191c32015-08-01 17:29:23 -070021#include <libgen.h>
Elliott Hughesa7090b92015-04-17 17:03:59 -070022#include <stdlib.h>
Elliott Hughes58305772015-04-17 13:57:15 -070023#include <sys/stat.h>
24#include <sys/types.h>
25#include <unistd.h>
26
Elliott Hughese67f1f82015-04-30 17:32:03 -070027#include <algorithm>
28
Elliott Hughes4f713192015-12-04 22:00:26 -080029#include <android-base/logging.h>
30#include <android-base/stringprintf.h>
31#include <android-base/strings.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070032
Josh Gao7d586072015-11-20 15:37:31 -080033#include "adb.h"
Elliott Hughese67f1f82015-04-30 17:32:03 -070034#include "adb_trace.h"
Elliott Hughes53daee62015-04-19 13:17:01 -070035#include "sysdeps.h"
36
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -070037#ifdef _WIN32
38# ifndef WIN32_LEAN_AND_MEAN
39# define WIN32_LEAN_AND_MEAN
40# endif
41# include "windows.h"
42# include "shlobj.h"
43#endif
44
Josh Gao787f3442015-11-03 18:52:35 -080045ADB_MUTEX_DEFINE(basename_lock);
Spencer Low22191c32015-08-01 17:29:23 -070046ADB_MUTEX_DEFINE(dirname_lock);
47
Josh Gao7d586072015-11-20 15:37:31 -080048#if defined(_WIN32)
49constexpr char kNullFileName[] = "NUL";
50#else
51constexpr char kNullFileName[] = "/dev/null";
52#endif
53
54void close_stdin() {
55 int fd = unix_open(kNullFileName, O_RDONLY);
56 if (fd == -1) {
57 fatal_errno("failed to open %s", kNullFileName);
58 }
59
60 if (TEMP_FAILURE_RETRY(dup2(fd, STDIN_FILENO)) == -1) {
61 fatal_errno("failed to redirect stdin to %s", kNullFileName);
62 }
63 unix_close(fd);
64}
65
Elliott Hughesa7090b92015-04-17 17:03:59 -070066bool getcwd(std::string* s) {
67 char* cwd = getcwd(nullptr, 0);
68 if (cwd != nullptr) *s = cwd;
69 free(cwd);
70 return (cwd != nullptr);
71}
72
Elliott Hughes58305772015-04-17 13:57:15 -070073bool directory_exists(const std::string& path) {
74 struct stat sb;
75 return lstat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
76}
77
Elliott Hughes58305772015-04-17 13:57:15 -070078std::string escape_arg(const std::string& s) {
Elliott Hughes5498ade2015-04-17 20:50:11 -070079 std::string result = s;
Elliott Hughes58305772015-04-17 13:57:15 -070080
Elliott Hughes84b0bf22015-05-15 12:06:00 -070081 // Escape any ' in the string (before we single-quote the whole thing).
82 // The correct way to do this for the shell is to replace ' with '\'' --- that is,
83 // close the existing single-quoted string, escape a single single-quote, and start
84 // a new single-quoted string. Like the C preprocessor, the shell will concatenate
85 // these pieces into one string.
86 for (size_t i = 0; i < s.size(); ++i) {
87 if (s[i] == '\'') {
88 result.insert(i, "'\\'");
89 i += 2;
90 }
Elliott Hughes58305772015-04-17 13:57:15 -070091 }
Elliott Hughes5498ade2015-04-17 20:50:11 -070092
93 // Prefix and suffix the whole string with '.
94 result.insert(result.begin(), '\'');
95 result.push_back('\'');
Elliott Hughes58305772015-04-17 13:57:15 -070096 return result;
97}
Elliott Hughese67f1f82015-04-30 17:32:03 -070098
Elliott Hughes5c742702015-07-30 17:42:01 -070099std::string adb_basename(const std::string& path) {
Josh Gao787f3442015-11-03 18:52:35 -0800100 // Copy path because basename may modify the string passed in.
101 std::string result(path);
102
103 // Use lock because basename() may write to a process global and return a
104 // pointer to that. Note that this locking strategy only works if all other
105 // callers to dirname in the process also grab this same lock.
106 adb_mutex_lock(&basename_lock);
107
108 // Note that if std::string uses copy-on-write strings, &str[0] will cause
109 // the copy to be made, so there is no chance of us accidentally writing to
110 // the storage for 'path'.
111 char* name = basename(&result[0]);
112
113 // In case dirname returned a pointer to a process global, copy that string
114 // before leaving the lock.
115 result.assign(name);
116
117 adb_mutex_unlock(&basename_lock);
118
119 return result;
Elliott Hughes5c742702015-07-30 17:42:01 -0700120}
121
Spencer Low22191c32015-08-01 17:29:23 -0700122std::string adb_dirname(const std::string& path) {
123 // Copy path because dirname may modify the string passed in.
Josh Gao787f3442015-11-03 18:52:35 -0800124 std::string result(path);
Spencer Low22191c32015-08-01 17:29:23 -0700125
126 // Use lock because dirname() may write to a process global and return a
127 // pointer to that. Note that this locking strategy only works if all other
128 // callers to dirname in the process also grab this same lock.
129 adb_mutex_lock(&dirname_lock);
130
131 // Note that if std::string uses copy-on-write strings, &str[0] will cause
132 // the copy to be made, so there is no chance of us accidentally writing to
133 // the storage for 'path'.
Josh Gao787f3442015-11-03 18:52:35 -0800134 char* parent = dirname(&result[0]);
Spencer Low22191c32015-08-01 17:29:23 -0700135
136 // In case dirname returned a pointer to a process global, copy that string
137 // before leaving the lock.
Josh Gao787f3442015-11-03 18:52:35 -0800138 result.assign(parent);
Spencer Low22191c32015-08-01 17:29:23 -0700139
140 adb_mutex_unlock(&dirname_lock);
141
142 return result;
Alex Vallée14216142015-05-06 17:22:25 -0400143}
144
Spencer Lowa1071c62016-02-10 15:03:50 -0800145// Given a relative or absolute filepath, create the directory hierarchy
Spencer Low22191c32015-08-01 17:29:23 -0700146// as needed. Returns true if the hierarchy is/was setup.
Elliott Hughes5c742702015-07-30 17:42:01 -0700147bool mkdirs(const std::string& path) {
Spencer Low22191c32015-08-01 17:29:23 -0700148 // TODO: all the callers do unlink && mkdirs && adb_creat ---
149 // that's probably the operation we should expose.
150
151 // Implementation Notes:
152 //
153 // Pros:
154 // - Uses dirname, so does not need to deal with OS_PATH_SEPARATOR.
155 // - On Windows, uses mingw dirname which accepts '/' and '\\', drive letters
156 // (C:\foo), UNC paths (\\server\share\dir\dir\file), and Unicode (when
157 // combined with our adb_mkdir() which takes UTF-8).
158 // - Is optimistic wrt thinking that a deep directory hierarchy will exist.
159 // So it does as few stat()s as possible before doing mkdir()s.
160 // Cons:
161 // - Recursive, so it uses stack space relative to number of directory
162 // components.
163
Josh Gao74e0fe72016-02-26 13:26:55 -0800164 // If path points to a symlink to a directory, that's fine.
165 struct stat sb;
166 if (stat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode)) {
Spencer Low22191c32015-08-01 17:29:23 -0700167 return true;
168 }
169
Spencer Lowa1071c62016-02-10 15:03:50 -0800170 const std::string parent(adb_dirname(path));
171
Spencer Low22191c32015-08-01 17:29:23 -0700172 // If dirname returned the same path as what we passed in, don't go recursive.
173 // This can happen on Windows when walking up the directory hierarchy and not
174 // finding anything that already exists (unlike POSIX that will eventually
175 // find . or /).
176 if (parent == path) {
177 errno = ENOENT;
178 return false;
179 }
180
Josh Gao45b6fc82015-11-04 14:51:23 -0800181 // Recursively make parent directories of 'path'.
Spencer Low22191c32015-08-01 17:29:23 -0700182 if (!mkdirs(parent)) {
183 return false;
184 }
185
Josh Gao45b6fc82015-11-04 14:51:23 -0800186 // Now that the parent directory hierarchy of 'path' has been ensured,
Spencer Lowa1071c62016-02-10 15:03:50 -0800187 // create path itself.
Josh Gao45b6fc82015-11-04 14:51:23 -0800188 if (adb_mkdir(path, 0775) == -1) {
Spencer Low22191c32015-08-01 17:29:23 -0700189 const int saved_errno = errno;
Spencer Lowa1071c62016-02-10 15:03:50 -0800190 // If someone else created the directory, that is ok.
191 if (directory_exists(path)) {
Spencer Low22191c32015-08-01 17:29:23 -0700192 return true;
193 }
Spencer Lowa1071c62016-02-10 15:03:50 -0800194 // There might be a pre-existing file at 'path', or there might have been some other error.
Spencer Low22191c32015-08-01 17:29:23 -0700195 errno = saved_errno;
196 return false;
197 }
198
199 return true;
Elliott Hughes5c742702015-07-30 17:42:01 -0700200}
201
Yabin Cuiaed3c612015-09-22 15:52:57 -0700202std::string dump_hex(const void* data, size_t byte_count) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700203 byte_count = std::min(byte_count, size_t(16));
204
205 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
206
207 std::string line;
208 for (size_t i = 0; i < byte_count; ++i) {
209 android::base::StringAppendF(&line, "%02x", p[i]);
210 }
211 line.push_back(' ');
212
213 for (size_t i = 0; i < byte_count; ++i) {
Spencer Low363af562015-11-07 18:51:54 -0800214 int ch = p[i];
215 line.push_back(isprint(ch) ? ch : '.');
Elliott Hughese67f1f82015-04-30 17:32:03 -0700216 }
217
Yabin Cuiaed3c612015-09-22 15:52:57 -0700218 return line;
Elliott Hughese67f1f82015-04-30 17:32:03 -0700219}
Elliott Hughes3d5f60d2015-07-18 12:21:30 -0700220
Elliott Hughesaa245492015-08-03 10:38:08 -0700221std::string perror_str(const char* msg) {
222 return android::base::StringPrintf("%s: %s", msg, strerror(errno));
223}
Yabin Cui6dfef252015-10-06 15:10:05 -0700224
225#if !defined(_WIN32)
Josh Gaoaddab3d2016-02-16 17:34:53 -0800226// Windows version provided in sysdeps_win32.cpp
Yabin Cui6dfef252015-10-06 15:10:05 -0700227bool set_file_block_mode(int fd, bool block) {
228 int flags = fcntl(fd, F_GETFL, 0);
229 if (flags == -1) {
230 PLOG(ERROR) << "failed to fcntl(F_GETFL) for fd " << fd;
231 return false;
232 }
233 flags = block ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
234 if (fcntl(fd, F_SETFL, flags) != 0) {
235 PLOG(ERROR) << "failed to fcntl(F_SETFL) for fd " << fd << ", flags " << flags;
236 return false;
237 }
238 return true;
239}
240#endif
Yurii Zubrytskyia9e2b992016-05-25 15:17:10 -0700241
242std::string adb_get_homedir_path(bool check_env_first) {
243#ifdef _WIN32
244 if (check_env_first) {
245 if (const char* const home = getenv("ANDROID_SDK_HOME")) {
246 return home;
247 }
248 }
249
250 WCHAR path[MAX_PATH];
251 const HRESULT hr = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path);
252 if (FAILED(hr)) {
253 D("SHGetFolderPathW failed: %s", android::base::SystemErrorCodeToString(hr).c_str());
254 return {};
255 }
256 std::string home_str;
257 if (!android::base::WideToUTF8(path, &home_str)) {
258 return {};
259 }
260 return home_str;
261#else
262 if (const char* const home = getenv("HOME")) {
263 return home;
264 }
265 return {};
266#endif
267}
268