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