bugreport.cpp revision 02ee1725ae93aa5821c78fdfbbd1ee9e95ef67dd
1/*
2 * Copyright (C) 2016 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 ADB
18
19#include "bugreport.h"
20
21#include <string>
22#include <vector>
23
24#include <android-base/strings.h>
25
26#include "sysdeps.h"
27#include "adb_utils.h"
28#include "file_sync_service.h"
29
30static constexpr char BUGZ_BEGIN_PREFIX[] = "BEGIN:";
31static constexpr char BUGZ_PROGRESS_PREFIX[] = "PROGRESS:";
32static constexpr char BUGZ_PROGRESS_SEPARATOR[] = "/";
33static constexpr char BUGZ_OK_PREFIX[] = "OK:";
34static constexpr char BUGZ_FAIL_PREFIX[] = "FAIL:";
35
36// Custom callback used to handle the output of zipped bugreports.
37class BugreportStandardStreamsCallback : public StandardStreamsCallbackInterface {
38  public:
39    BugreportStandardStreamsCallback(const std::string& dest_dir, const std::string& dest_file,
40                                     bool show_progress, Bugreport* br)
41        : br_(br),
42          src_file_(),
43          dest_dir_(dest_dir),
44          dest_file_(dest_file),
45          line_message_(),
46          invalid_lines_(),
47          show_progress_(show_progress),
48          status_(0),
49          line_() {
50        SetLineMessage("generating");
51    }
52
53    void OnStdout(const char* buffer, int length) {
54        for (int i = 0; i < length; i++) {
55            char c = buffer[i];
56            if (c == '\n') {
57                ProcessLine(line_);
58                line_.clear();
59            } else {
60                line_.append(1, c);
61            }
62        }
63    }
64
65    void OnStderr(const char* buffer, int length) {
66        OnStream(nullptr, stderr, buffer, length);
67    }
68    int Done(int unused_) {
69        // Process remaining line, if any.
70        ProcessLine(line_);
71
72        // Warn about invalid lines, if any.
73        if (!invalid_lines_.empty()) {
74            fprintf(stderr,
75                    "WARNING: bugreportz generated %zu line(s) with unknown commands, "
76                    "device might not support zipped bugreports:\n",
77                    invalid_lines_.size());
78            for (const auto& line : invalid_lines_) {
79                fprintf(stderr, "\t%s\n", line.c_str());
80            }
81            fprintf(stderr,
82                    "If the zipped bugreport was not generated, try 'adb bugreport' instead.\n");
83        }
84
85        // Pull the generated bug report.
86        if (status_ == 0) {
87            if (src_file_.empty()) {
88                fprintf(stderr, "bugreportz did not return a '%s' or '%s' line\n", BUGZ_OK_PREFIX,
89                        BUGZ_FAIL_PREFIX);
90                return -1;
91            }
92            std::string destination;
93            if (dest_dir_.empty()) {
94                destination = dest_file_;
95            } else {
96                destination = android::base::StringPrintf("%s%c%s", dest_dir_.c_str(),
97                                                          OS_PATH_SEPARATOR, dest_file_.c_str());
98            }
99            std::vector<const char*> srcs{src_file_.c_str()};
100            SetLineMessage("pulling");
101            status_ =
102                br_->DoSyncPull(srcs, destination.c_str(), true, line_message_.c_str()) ? 0 : 1;
103            if (status_ != 0) {
104                fprintf(stderr,
105                        "Bug report finished but could not be copied to '%s'.\n"
106                        "Try to run 'adb pull %s <directory>'\n"
107                        "to copy it to a directory that can be written.\n",
108                        destination.c_str(), src_file_.c_str());
109            }
110        }
111        return status_;
112    }
113
114  private:
115    void SetLineMessage(const std::string& action) {
116        line_message_ = action + " " + adb_basename(dest_file_);
117    }
118
119    void SetSrcFile(const std::string path) {
120        src_file_ = path;
121        if (!dest_dir_.empty()) {
122            // Only uses device-provided name when user passed a directory.
123            dest_file_ = adb_basename(path);
124            SetLineMessage("generating");
125        }
126    }
127
128    void ProcessLine(const std::string& line) {
129        if (line.empty()) return;
130
131        if (android::base::StartsWith(line, BUGZ_BEGIN_PREFIX)) {
132            SetSrcFile(&line[strlen(BUGZ_BEGIN_PREFIX)]);
133        } else if (android::base::StartsWith(line, BUGZ_OK_PREFIX)) {
134            SetSrcFile(&line[strlen(BUGZ_OK_PREFIX)]);
135        } else if (android::base::StartsWith(line, BUGZ_FAIL_PREFIX)) {
136            const char* error_message = &line[strlen(BUGZ_FAIL_PREFIX)];
137            fprintf(stderr, "Device failed to take a zipped bugreport: %s\n", error_message);
138            status_ = -1;
139        } else if (show_progress_ && android::base::StartsWith(line, BUGZ_PROGRESS_PREFIX)) {
140            // progress_line should have the following format:
141            //
142            // BUGZ_PROGRESS_PREFIX:PROGRESS/TOTAL
143            //
144            size_t idx1 = line.rfind(BUGZ_PROGRESS_PREFIX) + strlen(BUGZ_PROGRESS_PREFIX);
145            size_t idx2 = line.rfind(BUGZ_PROGRESS_SEPARATOR);
146            int progress = std::stoi(line.substr(idx1, (idx2 - idx1)));
147            int total = std::stoi(line.substr(idx2 + 1));
148            br_->UpdateProgress(line_message_, progress, total);
149        } else {
150            invalid_lines_.push_back(line);
151        }
152    }
153
154    Bugreport* br_;
155
156    // Path of bugreport on device.
157    std::string src_file_;
158
159    // Bugreport destination on host, depending on argument passed on constructor:
160    // - if argument is a directory, dest_dir_ is set with it and dest_file_ will be the name
161    //   of the bugreport reported by the device.
162    // - if argument is empty, dest_dir is set as the current directory and dest_file_ will be the
163    //   name of the bugreport reported by the device.
164    // - otherwise, dest_dir_ is not set and dest_file_ is set with the value passed on constructor.
165    std::string dest_dir_, dest_file_;
166
167    // Message displayed on LinePrinter, it's updated every time the destination above change.
168    std::string line_message_;
169
170    // Lines sent by bugreportz that contain invalid commands; will be displayed at the end.
171    std::vector<std::string> invalid_lines_;
172
173    // Whether PROGRESS_LINES should be interpreted as progress.
174    bool show_progress_;
175
176    // Overall process of the operation, as returned by Done().
177    int status_;
178
179    // Temporary buffer containing the characters read since the last newline (\n).
180    std::string line_;
181
182    DISALLOW_COPY_AND_ASSIGN(BugreportStandardStreamsCallback);
183};
184
185// Implemented in commandline.cpp
186int usage();
187
188int Bugreport::DoIt(TransportType transport_type, const char* serial, int argc, const char** argv) {
189    if (argc > 2) return usage();
190
191    // Gets bugreportz version.
192    std::string bugz_stdout, bugz_stderr;
193    DefaultStandardStreamsCallback version_callback(&bugz_stdout, &bugz_stderr);
194    int status = SendShellCommand(transport_type, serial, "bugreportz -v", false, &version_callback);
195    std::string bugz_version = android::base::Trim(bugz_stderr);
196    std::string bugz_output = android::base::Trim(bugz_stdout);
197
198    if (status != 0 || bugz_version.empty()) {
199        D("'bugreportz' -v results: status=%d, stdout='%s', stderr='%s'", status,
200          bugz_output.c_str(), bugz_version.c_str());
201        if (argc == 1) {
202            // Device does not support bugreportz: if called as 'adb bugreport', just falls out to
203            // the flat-file version.
204            fprintf(stderr,
205                    "Failed to get bugreportz version, which is only available on devices "
206                    "running Android 7.0 or later.\nTrying a plain-text bug report instead.\n");
207            return SendShellCommand(transport_type, serial, "bugreport", false);
208        }
209
210        // But if user explicitly asked for a zipped bug report, fails instead (otherwise calling
211        // 'bugreport' would generate a lot of output the user might not be prepared to handle).
212        fprintf(stderr,
213                "Failed to get bugreportz version: 'bugreportz -v' returned '%s' (code %d).\n"
214                "If the device does not run Android 7.0 or above, try 'adb bugreport' instead.\n",
215                bugz_output.c_str(), status);
216        return status != 0 ? status : -1;
217    }
218
219    std::string dest_file, dest_dir;
220
221    if (argc == 1) {
222        // No args - use current directory
223        if (!getcwd(&dest_dir)) {
224            perror("adb: getcwd failed");
225            return 1;
226        }
227    } else {
228        // Check whether argument is a directory or file
229        if (directory_exists(argv[1])) {
230            dest_dir = argv[1];
231        } else {
232            dest_file = argv[1];
233        }
234    }
235
236    if (dest_file.empty()) {
237        // Uses a default value until device provides the proper name
238        dest_file = "bugreport.zip";
239    } else {
240        if (!android::base::EndsWithIgnoreCase(dest_file, ".zip")) {
241            dest_file += ".zip";
242        }
243    }
244
245    bool show_progress = true;
246    std::string bugz_command = "bugreportz -p";
247    if (bugz_version == "1.0") {
248        // 1.0 does not support progress notifications, so print a disclaimer
249        // message instead.
250        fprintf(stderr,
251                "Bugreport is in progress and it could take minutes to complete.\n"
252                "Please be patient and do not cancel or disconnect your device "
253                "until it completes.\n");
254        show_progress = false;
255        bugz_command = "bugreportz";
256    }
257    BugreportStandardStreamsCallback bugz_callback(dest_dir, dest_file, show_progress, this);
258    return SendShellCommand(transport_type, serial, bugz_command, false, &bugz_callback);
259}
260
261void Bugreport::UpdateProgress(const std::string& message, int progress, int total) {
262    int progress_percentage = (progress * 100 / total);
263    line_printer_.Print(
264        android::base::StringPrintf("[%3d%%] %s", progress_percentage, message.c_str()),
265        LinePrinter::INFO);
266}
267
268int Bugreport::SendShellCommand(TransportType transport_type, const char* serial,
269                                const std::string& command, bool disable_shell_protocol,
270                                StandardStreamsCallbackInterface* callback) {
271    return send_shell_command(transport_type, serial, command, disable_shell_protocol, callback);
272}
273
274bool Bugreport::DoSyncPull(const std::vector<const char*>& srcs, const char* dst, bool copy_attrs,
275                           const char* name) {
276    return do_sync_pull(srcs, dst, copy_attrs, name);
277}
278