adb_utils.cpp revision 459df8f3a14d4c614f0211049800cf7cad6d30ad
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#define TRACE_TAG TRACE_ADB
18
19#include "adb_utils.h"
20
21#include <stdlib.h>
22#include <sys/stat.h>
23#include <sys/types.h>
24#include <unistd.h>
25
26#include <algorithm>
27
28#include <base/stringprintf.h>
29
30#include "adb_trace.h"
31#include "sysdeps.h"
32
33bool getcwd(std::string* s) {
34  char* cwd = getcwd(nullptr, 0);
35  if (cwd != nullptr) *s = cwd;
36  free(cwd);
37  return (cwd != nullptr);
38}
39
40bool directory_exists(const std::string& path) {
41  struct stat sb;
42  return lstat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode);
43}
44
45bool file_exists(const std::string& path) {
46  struct stat sb;
47  return lstat(path.c_str(), &sb) != -1 && S_ISREG(sb.st_mode);
48}
49
50std::string escape_arg(const std::string& s) {
51  std::string result = s;
52
53  // Escape any ' in the string (before we single-quote the whole thing).
54  // The correct way to do this for the shell is to replace ' with '\'' --- that is,
55  // close the existing single-quoted string, escape a single single-quote, and start
56  // a new single-quoted string. Like the C preprocessor, the shell will concatenate
57  // these pieces into one string.
58  for (size_t i = 0; i < s.size(); ++i) {
59    if (s[i] == '\'') {
60      result.insert(i, "'\\'");
61      i += 2;
62    }
63  }
64
65  // Prefix and suffix the whole string with '.
66  result.insert(result.begin(), '\'');
67  result.push_back('\'');
68  return result;
69}
70
71void dump_hex(const void* data, size_t byte_count) {
72    byte_count = std::min(byte_count, size_t(16));
73
74    const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
75
76    std::string line;
77    for (size_t i = 0; i < byte_count; ++i) {
78        android::base::StringAppendF(&line, "%02x", p[i]);
79    }
80    line.push_back(' ');
81
82    for (size_t i = 0; i < byte_count; ++i) {
83        int c = p[i];
84        if (c < 32 || c > 127) {
85            c = '.';
86        }
87        line.push_back(c);
88    }
89
90    DR("%s\n", line.c_str());
91}
92