• 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                 fprintf(stderr,
109                         "Bug report finished but could not be copied to '%s'.\n"
110                         "Try to run 'adb pull %s <directory>'\n"
111                         "to copy it to a directory that can be written.\n",
112                         destination.c_str(), src_file_.c_str());
113             }
114         }
115         return status_;
116     }
117 
118   private:
SetLineMessage(const std::string & action)119     void SetLineMessage(const std::string& action) {
120         line_message_ = action + " " + android::base::Basename(dest_file_);
121     }
122 
SetSrcFile(const std::string path)123     void SetSrcFile(const std::string path) {
124         src_file_ = path;
125         if (!dest_dir_.empty()) {
126             // Only uses device-provided name when user passed a directory.
127             dest_file_ = android::base::Basename(path);
128             SetLineMessage("generating");
129         }
130     }
131 
ProcessLine(const std::string & line)132     void ProcessLine(const std::string& line) {
133         if (line.empty()) return;
134 
135         if (android::base::StartsWith(line, BUGZ_BEGIN_PREFIX)) {
136             SetSrcFile(&line[strlen(BUGZ_BEGIN_PREFIX)]);
137         } else if (android::base::StartsWith(line, BUGZ_OK_PREFIX)) {
138             SetSrcFile(&line[strlen(BUGZ_OK_PREFIX)]);
139         } else if (android::base::StartsWith(line, BUGZ_FAIL_PREFIX)) {
140             const char* error_message = &line[strlen(BUGZ_FAIL_PREFIX)];
141             fprintf(stderr, "adb: device failed to take a zipped bugreport: %s\n", error_message);
142             status_ = -1;
143         } else if (show_progress_ && android::base::StartsWith(line, BUGZ_PROGRESS_PREFIX)) {
144             // progress_line should have the following format:
145             //
146             // BUGZ_PROGRESS_PREFIX:PROGRESS/TOTAL
147             //
148             size_t idx1 = line.rfind(BUGZ_PROGRESS_PREFIX) + strlen(BUGZ_PROGRESS_PREFIX);
149             size_t idx2 = line.rfind(BUGZ_PROGRESS_SEPARATOR);
150             int progress = std::stoi(line.substr(idx1, (idx2 - idx1)));
151             int total = std::stoi(line.substr(idx2 + 1));
152             int progress_percentage = (progress * 100 / total);
153             if (progress_percentage != 0 && progress_percentage <= last_progress_percentage_) {
154                 // Ignore.
155                 return;
156             }
157             last_progress_percentage_ = progress_percentage;
158             br_->UpdateProgress(line_message_, progress_percentage);
159         } else {
160             invalid_lines_.push_back(line);
161         }
162     }
163 
164     Bugreport* br_;
165 
166     // Path of bugreport on device.
167     std::string src_file_;
168 
169     // Bugreport destination on host, depending on argument passed on constructor:
170     // - if argument is a directory, dest_dir_ is set with it and dest_file_ will be the name
171     //   of the bugreport reported by the device.
172     // - if argument is empty, dest_dir is set as the current directory and dest_file_ will be the
173     //   name of the bugreport reported by the device.
174     // - otherwise, dest_dir_ is not set and dest_file_ is set with the value passed on constructor.
175     std::string dest_dir_, dest_file_;
176 
177     // Message displayed on LinePrinter, it's updated every time the destination above change.
178     std::string line_message_;
179 
180     // Lines sent by bugreportz that contain invalid commands; will be displayed at the end.
181     std::vector<std::string> invalid_lines_;
182 
183     // Whether PROGRESS_LINES should be interpreted as progress.
184     bool show_progress_;
185 
186     // Overall process of the operation, as returned by Done().
187     int status_;
188 
189     // Temporary buffer containing the characters read since the last newline (\n).
190     std::string line_;
191 
192     // Last displayed progress.
193     // Since dumpstate progress can recede, only forward progress should be displayed
194     int last_progress_percentage_;
195 
196     DISALLOW_COPY_AND_ASSIGN(BugreportStandardStreamsCallback);
197 };
198 
DoIt(int argc,const char ** argv)199 int Bugreport::DoIt(int argc, const char** argv) {
200     if (argc > 2) error_exit("usage: adb bugreport [PATH]");
201 
202     // Gets bugreportz version.
203     std::string bugz_stdout, bugz_stderr;
204     DefaultStandardStreamsCallback version_callback(&bugz_stdout, &bugz_stderr);
205     int status = SendShellCommand("bugreportz -v", false, &version_callback);
206     std::string bugz_version = android::base::Trim(bugz_stderr);
207     std::string bugz_output = android::base::Trim(bugz_stdout);
208 
209     if (status != 0 || bugz_version.empty()) {
210         D("'bugreportz' -v results: status=%d, stdout='%s', stderr='%s'", status,
211           bugz_output.c_str(), bugz_version.c_str());
212         if (argc == 1) {
213             // Device does not support bugreportz: if called as 'adb bugreport', just falls out to
214             // the flat-file version.
215             fprintf(stderr,
216                     "Failed to get bugreportz version, which is only available on devices "
217                     "running Android 7.0 or later.\nTrying a plain-text bug report instead.\n");
218             return SendShellCommand("bugreport", false);
219         }
220 
221         // But if user explicitly asked for a zipped bug report, fails instead (otherwise calling
222         // 'bugreport' would generate a lot of output the user might not be prepared to handle).
223         fprintf(stderr,
224                 "Failed to get bugreportz version: 'bugreportz -v' returned '%s' (code %d).\n"
225                 "If the device does not run Android 7.0 or above, try 'adb bugreport' instead.\n",
226                 bugz_output.c_str(), status);
227         return status != 0 ? status : -1;
228     }
229 
230     std::string dest_file, dest_dir;
231 
232     if (argc == 1) {
233         // No args - use current directory
234         if (!getcwd(&dest_dir)) {
235             perror("adb: getcwd failed");
236             return 1;
237         }
238     } else {
239         // Check whether argument is a directory or file
240         if (directory_exists(argv[1])) {
241             dest_dir = argv[1];
242         } else {
243             dest_file = argv[1];
244         }
245     }
246 
247     if (dest_file.empty()) {
248         // Uses a default value until device provides the proper name
249         dest_file = "bugreport.zip";
250     } else {
251         if (!android::base::EndsWithIgnoreCase(dest_file, ".zip")) {
252             dest_file += ".zip";
253         }
254     }
255 
256     bool show_progress = true;
257     std::string bugz_command = "bugreportz -p";
258     if (bugz_version == "1.0") {
259         // 1.0 does not support progress notifications, so print a disclaimer
260         // message instead.
261         fprintf(stderr,
262                 "Bugreport is in progress and it could take minutes to complete.\n"
263                 "Please be patient and do not cancel or disconnect your device "
264                 "until it completes.\n");
265         show_progress = false;
266         bugz_command = "bugreportz";
267     }
268     BugreportStandardStreamsCallback bugz_callback(dest_dir, dest_file, show_progress, this);
269     return SendShellCommand(bugz_command, false, &bugz_callback);
270 }
271 
UpdateProgress(const std::string & message,int progress_percentage)272 void Bugreport::UpdateProgress(const std::string& message, int progress_percentage) {
273     line_printer_.Print(
274         android::base::StringPrintf("[%3d%%] %s", progress_percentage, message.c_str()),
275         LinePrinter::INFO);
276 }
277 
SendShellCommand(const std::string & command,bool disable_shell_protocol,StandardStreamsCallbackInterface * callback)278 int Bugreport::SendShellCommand(const std::string& command, bool disable_shell_protocol,
279                                 StandardStreamsCallbackInterface* callback) {
280     return send_shell_command(command, disable_shell_protocol, callback);
281 }
282 
DoSyncPull(const std::vector<const char * > & srcs,const char * dst,bool copy_attrs,const char * name)283 bool Bugreport::DoSyncPull(const std::vector<const char*>& srcs, const char* dst, bool copy_attrs,
284                            const char* name) {
285     return do_sync_pull(srcs, dst, copy_attrs, name);
286 }
287