blob: 97ce712b0a2c46b955067bf8402abc35071cb908 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
adlr@google.com3defe6a2009-12-04 20:57:17 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -07006
Ben Chan9abb7632014-08-07 00:10:53 -07007#include <stdint.h>
8
adlr@google.com3defe6a2009-12-04 20:57:17 +00009#include <dirent.h>
Alex Deymoc1711e22014-08-08 13:16:23 -070010#include <elf.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000011#include <errno.h>
Alex Deymo192393b2014-11-10 15:58:38 -080012#include <ext2fs/ext2fs.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080013#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000014#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070017#include <sys/mount.h>
18#include <sys/resource.h>
19#include <sys/stat.h>
20#include <sys/types.h>
21#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000022#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070023
adlr@google.com3defe6a2009-12-04 20:57:17 +000024#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070025#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070026#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070027
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070028#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070029#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080030#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070031#include <base/files/scoped_file.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070032#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040033#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080034#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050035#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070036#include <base/strings/string_number_conversions.h>
37#include <base/strings/string_split.h>
38#include <base/strings/string_util.h>
39#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080040#include <chromeos/data_encoding.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070041#include <chromeos/message_loops/message_loop.h>
Will Drewry8f71da82010-08-30 14:07:11 -050042
David Zeuthen33bae492014-02-25 16:16:18 -080043#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070044#include "update_engine/constants.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080045#include "update_engine/file_descriptor.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080046#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070047#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080048#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070049#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080050#include "update_engine/system_state.h"
51#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000052
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070053using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080054using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000055using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070056using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000057using std::string;
58using std::vector;
59
60namespace chromeos_update_engine {
61
Ben Chan77a1eba2012-10-07 22:54:55 -070062namespace {
63
64// The following constants control how UnmountFilesystem should retry if
65// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
66// one second.
67const int kUnmountMaxNumOfRetries = 5;
68const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070069
70// Number of bytes to read from a file to attempt to detect its contents. Used
71// in GetFileFormat.
72const int kGetFileFormatMaxHeaderSize = 32;
73
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080074// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
75// simply based on the name of the device.
76bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070077 return base::StartsWithASCII(disk_name, "/dev/ubi", true) ||
78 base::StartsWithASCII(disk_name, "/dev/mtd", true);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080079}
80
81// Return the device name for the corresponding partition on a NAND device.
82// WARNING: This function returns device names that are not mountable.
83string MakeNandPartitionName(int partition_num) {
84 switch (partition_num) {
85 case 2:
86 case 4:
87 case 6: {
88 return base::StringPrintf("/dev/mtd%d", partition_num);
89 }
90 default: {
91 return base::StringPrintf("/dev/ubi%d_0", partition_num);
92 }
93 }
94}
95
96// Return the device name for the corresponding partition on a NAND device that
97// may be mountable (but may not be writable).
98string MakeNandPartitionNameForMount(int partition_num) {
99 switch (partition_num) {
100 case 2:
101 case 4:
102 case 6: {
103 return base::StringPrintf("/dev/mtd%d", partition_num);
104 }
105 case 3:
106 case 5:
107 case 7: {
108 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
109 }
110 default: {
111 return base::StringPrintf("/dev/ubi%d_0", partition_num);
112 }
113 }
114}
115
Ben Chan77a1eba2012-10-07 22:54:55 -0700116} // namespace
117
adlr@google.com3defe6a2009-12-04 20:57:17 +0000118namespace utils {
119
Chris Sosa4f8ee272012-11-30 13:01:54 -0800120// Cgroup container is created in update-engine's upstart script located at
121// /etc/init/update-engine.conf.
122static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
123
J. Richard Barnette63137e52013-10-28 10:57:29 -0700124string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700125 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700126
Alex Vakulenko75039d72014-03-25 12:36:28 -0700127 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700128 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700129 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700130 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800131 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700132 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800133 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700134 string output;
135 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800136 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700137 return output;
138 }
139 }
140 }
141 LOG(ERROR) << "Unable to parse fwid from ec info.";
142 return "";
143}
144
145
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700146const string KernelDeviceOfBootDevice(const string& boot_device) {
147 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700148
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700149 string disk_name;
150 int partition_num;
151 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700152 // Currently this assumes the partition number of the boot device is
153 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
154 // get the kernel device.
155 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
156 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
157 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700158 }
159
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700160 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700161}
162
163
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800164bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800165 DirectFileWriter writer;
166 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
167 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700168 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800169 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800170 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800171 return true;
172}
173
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700174bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700175 const char* c_buf = static_cast<const char*>(buf);
176 ssize_t bytes_written = 0;
177 while (bytes_written < static_cast<ssize_t>(count)) {
178 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
179 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
180 bytes_written += rc;
181 }
182 return true;
183}
184
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700185bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
186 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700187 size_t bytes_written = 0;
188 int num_attempts = 0;
189 while (bytes_written < count) {
190 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700191 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
192 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700193 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
194 if (rc < 0) {
195 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
196 << " bytes_written=" << bytes_written
197 << " count=" << count << " offset=" << offset;
198 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700199 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
200 bytes_written += rc;
201 }
202 return true;
203}
204
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800205bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
206 const char* c_buf = static_cast<const char*>(buf);
207 ssize_t bytes_written = 0;
208 while (bytes_written < static_cast<ssize_t>(count)) {
209 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
210 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
211 bytes_written += rc;
212 }
213 return true;
214}
215
216bool PWriteAll(FileDescriptorPtr fd,
217 const void* buf,
218 size_t count,
219 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700220 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
221 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800222 return WriteAll(fd, buf, count);
223}
224
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700225bool PReadAll(int fd, void* buf, size_t count, off_t offset,
226 ssize_t* out_bytes_read) {
227 char* c_buf = static_cast<char*>(buf);
228 ssize_t bytes_read = 0;
229 while (bytes_read < static_cast<ssize_t>(count)) {
230 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
231 offset + bytes_read);
232 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
233 if (rc == 0) {
234 break;
235 }
236 bytes_read += rc;
237 }
238 *out_bytes_read = bytes_read;
239 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700240}
241
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800242bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
243 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700244 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
245 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800246 char* c_buf = static_cast<char*>(buf);
247 ssize_t bytes_read = 0;
248 while (bytes_read < static_cast<ssize_t>(count)) {
249 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
250 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
251 if (rc == 0) {
252 break;
253 }
254 bytes_read += rc;
255 }
256 *out_bytes_read = bytes_read;
257 return true;
258}
259
Gilad Arnold19a45f02012-07-19 12:36:10 -0700260// Append |nbytes| of content from |buf| to the vector pointed to by either
261// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800262static void AppendBytes(const uint8_t* buf, size_t nbytes,
263 chromeos::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700264 CHECK(buf);
265 CHECK(vec_p);
266 vec_p->insert(vec_p->end(), buf, buf + nbytes);
267}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800268static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700269 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700270 CHECK(buf);
271 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800272 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700273}
274
275// Reads from an open file |fp|, appending the read content to the container
276// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200277// file's content, false otherwise. If |size| is not -1, reads up to |size|
278// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700279template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200280static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700281 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200282 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800283 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200284 while (size == -1 || size > 0) {
285 off_t bytes_to_read = sizeof(buf);
286 if (size > 0 && bytes_to_read > size) {
287 bytes_to_read = size;
288 }
289 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
290 if (!nbytes) {
291 break;
292 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700293 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200294 if (size != -1) {
295 CHECK(size >= static_cast<off_t>(nbytes));
296 size -= nbytes;
297 }
298 }
299 if (ferror(fp)) {
300 return false;
301 }
302 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700303}
304
Darin Petkov8e447e02013-04-16 16:23:50 +0200305// Opens a file |path| for reading and appends its the contents to a container
306// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
307// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700308template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700309static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200310 off_t offset,
311 off_t size,
312 T* out_p) {
313 CHECK_GE(offset, 0);
314 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700315 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200316 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000317 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200318 if (offset) {
319 // Return success without appending any data if a chunk beyond the end of
320 // the file is requested.
321 if (offset >= FileSize(path)) {
322 return true;
323 }
324 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
325 }
326 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000327}
328
Alex Deymo10875d92014-11-10 21:52:57 -0800329// TODO(deymo): This is only used in unittest, but requires the private
330// Read<string>() defined here. Expose Read<string>() or move to base/ version.
331bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700332 FILE* fp = popen(cmd.c_str(), "r");
333 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000334 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200335 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700336 return (success && pclose(fp) >= 0);
337}
338
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800339bool ReadFile(const string& path, chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200340 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700341}
342
Darin Petkov8e447e02013-04-16 16:23:50 +0200343bool ReadFile(const string& path, string* out_p) {
344 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700345}
346
Darin Petkov8e447e02013-04-16 16:23:50 +0200347bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800348 chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200349 return ReadFileChunkAndAppend(path, offset, size, out_p);
350}
351
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700352off_t BlockDevSize(int fd) {
353 uint64_t dev_size;
354 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
355 if (rc == -1) {
356 dev_size = -1;
357 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
358 }
359 return dev_size;
360}
361
362off_t BlockDevSize(const string& path) {
363 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
364 if (fd == -1) {
365 PLOG(ERROR) << "Error opening " << path;
366 return fd;
367 }
368
369 off_t dev_size = BlockDevSize(fd);
370 if (dev_size == -1)
371 PLOG(ERROR) << "Error getting block device size on " << path;
372
373 close(fd);
374 return dev_size;
375}
376
377off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700378 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700379 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700380 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700381 if (rc < 0) {
382 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700383 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700384 }
385 if (S_ISREG(stbuf.st_mode))
386 return stbuf.st_size;
387 if (S_ISBLK(stbuf.st_mode))
388 return BlockDevSize(fd);
389 LOG(ERROR) << "Couldn't determine the type of " << fd;
390 return -1;
391}
392
393off_t FileSize(const string& path) {
394 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
395 if (fd == -1) {
396 PLOG(ERROR) << "Error opening " << path;
397 return fd;
398 }
399 off_t size = FileSize(fd);
400 if (size == -1)
401 PLOG(ERROR) << "Error getting file size of " << path;
402 close(fd);
403 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700404}
405
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800406void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000407 LOG(INFO) << "Logging array of length: " << length;
408 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700409 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000410 const unsigned int bytes_remaining = length - i;
411 const unsigned int bytes_per_this_line = min(bytes_per_line,
412 bytes_remaining);
413 char header[100];
414 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
415 TEST_AND_RETURN(r == 13);
416 string line = header;
417 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
418 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800419 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000420 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
421 TEST_AND_RETURN(r == 3);
422 line += buf;
423 }
424 LOG(INFO) << line;
425 }
426}
427
Alex Deymof329b932014-10-30 01:37:48 -0700428string GetDiskName(const string& partition_name) {
429 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800430 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700431 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700432}
433
Alex Deymof329b932014-10-30 01:37:48 -0700434int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800435 int partition_num = 0;
436 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
437 partition_num : 0;
438}
439
Alex Deymof329b932014-10-30 01:37:48 -0700440bool SplitPartitionName(const string& partition_name,
441 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800442 int* out_partition_num) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700443 if (!base::StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800444 LOG(ERROR) << "Invalid partition device name: " << partition_name;
445 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700446 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800447
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700448 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
449 if (last_nondigit_pos == string::npos ||
450 (last_nondigit_pos + 1) == partition_name.size()) {
451 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800452 return false;
453 }
454
Alex Deymof329b932014-10-30 01:37:48 -0700455 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700456 if (partition_name[last_nondigit_pos] == '_') {
457 // NAND block devices have weird naming which could be something
458 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
459 size_t prev_nondigit_pos =
460 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
461 if (prev_nondigit_pos == string::npos ||
462 (prev_nondigit_pos + 1) == last_nondigit_pos) {
463 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
464 return false;
465 }
466
467 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
468 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800469 }
470
471 if (out_disk_name) {
472 // Special case for MMC devices which have the following naming scheme:
473 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700474 size_t disk_name_len = last_nondigit_pos;
475 if (partition_name[last_nondigit_pos] != 'p' ||
476 last_nondigit_pos == 0 ||
477 !isdigit(partition_name[last_nondigit_pos - 1])) {
478 disk_name_len++;
479 }
480 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800481 }
482
483 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700484 string partition_str = partition_name.substr(last_nondigit_pos + 1,
485 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800486 *out_partition_num = atoi(partition_str.c_str());
487 }
488 return true;
489}
490
Alex Deymof329b932014-10-30 01:37:48 -0700491string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800492 if (partition_num < 1) {
493 LOG(ERROR) << "Invalid partition number: " << partition_num;
494 return string();
495 }
496
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700497 if (!base::StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800498 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700499 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800500 }
501
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800502 if (IsMtdDeviceName(disk_name)) {
503 // Special case for UBI block devices.
504 // 1. ubiblock is not writable, we need to use plain "ubi".
505 // 2. There is a "_0" suffix.
506 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800507 }
508
Alex Deymof329b932014-10-30 01:37:48 -0700509 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700510 if (isdigit(partition_name.back())) {
511 // Special case for devices with names ending with a digit.
512 // Add "p" to separate the disk name from partition number,
513 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800514 partition_name += 'p';
515 }
516
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700517 partition_name += std::to_string(partition_num);
518
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800519 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700520}
521
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800522string MakePartitionNameForMount(const string& part_name) {
523 if (IsMtdDeviceName(part_name)) {
524 int partition_num;
525 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
526 return "";
527 }
528 return MakeNandPartitionNameForMount(partition_num);
529 }
530 return part_name;
531}
532
Darin Petkovf74eb652010-08-04 12:08:38 -0700533string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700534 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700535 if (device_path.DirName().value() != "/dev") {
536 return "";
537 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700538 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700539}
540
Alex Deymof329b932014-10-30 01:37:48 -0700541bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700542 string sysfs_block = SysfsBlockDevice(device);
543 string removable;
544 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700545 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700546 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700547 return false;
548 }
Ben Chan736fcb52014-05-21 18:28:22 -0700549 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700550 return removable == "1";
551}
552
Alex Deymof329b932014-10-30 01:37:48 -0700553string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000554 char buf[100];
555 buf[0] = '\0';
556 return strerror_r(err, buf, sizeof(buf));
557}
558
adlr@google.com3defe6a2009-12-04 20:57:17 +0000559bool FileExists(const char* path) {
560 struct stat stbuf;
561 return 0 == lstat(path, &stbuf);
562}
563
Darin Petkov30291ed2010-11-12 10:23:06 -0800564bool IsSymlink(const char* path) {
565 struct stat stbuf;
566 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
567}
568
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800569bool TryAttachingUbiVolume(int volume_num, int timeout) {
570 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
571 if (FileExists(volume_path.c_str())) {
572 return true;
573 }
574
575 int exit_code;
576 vector<string> cmd = {
577 "ubiattach",
578 "-m",
579 base::StringPrintf("%d", volume_num),
580 "-d",
581 base::StringPrintf("%d", volume_num)
582 };
583 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
584 TEST_AND_RETURN_FALSE(exit_code == 0);
585
586 cmd = {
587 "ubiblock",
588 "--create",
589 volume_path
590 };
591 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
592 TEST_AND_RETURN_FALSE(exit_code == 0);
593
594 while (timeout > 0 && !FileExists(volume_path.c_str())) {
595 sleep(1);
596 timeout--;
597 }
598
599 return FileExists(volume_path.c_str());
600}
601
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800602// If |path| is absolute, or explicit relative to the current working directory,
603// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
604// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
605// resulting path.
606static const string PrependTmpdir(const string& path) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700607 if (path[0] == '/' || base::StartsWithASCII(path, "./", true) ||
608 base::StartsWithASCII(path, "../", true))
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800609 return path;
610
611 const char *tmpdir = getenv("TMPDIR");
612 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
613 return prefix + "/" + path;
614}
615
Alex Deymof329b932014-10-30 01:37:48 -0700616bool MakeTempFile(const string& base_filename_template,
617 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700618 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800619 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700620 DCHECK(filename || fd);
621 vector<char> buf(filename_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800622 memcpy(buf.data(), filename_template.data(), filename_template.size());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700623 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700624
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800625 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700626 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
627 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800628 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700629 }
630 if (fd) {
631 *fd = mkstemp_fd;
632 } else {
633 close(mkstemp_fd);
634 }
635 return true;
636}
637
Alex Deymof329b932014-10-30 01:37:48 -0700638bool MakeTempDirectory(const string& base_dirname_template,
639 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800640 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700641 DCHECK(dirname);
642 vector<char> buf(dirname_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800643 memcpy(buf.data(), dirname_template.data(), dirname_template.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700644 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700645
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800646 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700647 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800648 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700649 return true;
650}
651
adlr@google.com3defe6a2009-12-04 20:57:17 +0000652bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700653 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700654 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800655 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
656 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
657 for (const char* fstype : fstypes) {
658 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
659 nullptr);
660 if (rc == 0)
661 return true;
662
663 PLOG(WARNING) << "Unable to mount destination device " << device
664 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000665 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800666 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
667 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000668}
669
670bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700671 for (int num_retries = 0; ; ++num_retries) {
672 if (umount(mountpoint.c_str()) == 0)
673 break;
674
675 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
676 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700677 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700678 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000679 return true;
680}
681
Alex Deymof329b932014-10-30 01:37:48 -0700682bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700683 int* out_block_count,
684 int* out_block_size) {
685 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700686 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700687 ScopedFdCloser fd_closer(&fd);
688 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
689}
690
691bool GetFilesystemSizeFromFD(int fd,
692 int* out_block_count,
693 int* out_block_size) {
694 TEST_AND_RETURN_FALSE(fd >= 0);
695
Alex Deymo192393b2014-11-10 15:58:38 -0800696 // Determine the filesystem size by directly reading the block count and
697 // block size information from the superblock. Supported FS are ext3 and
698 // squashfs.
699
700 // Read from the fd only once and detect in memory. The first 2 KiB is enough
701 // to read the ext2 superblock (located at offset 1024) and the squashfs
702 // superblock (located at offset 0).
703 const ssize_t kBufferSize = 2048;
704
705 uint8_t buffer[kBufferSize];
706 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
707 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700708 return false;
709 }
Alex Deymo192393b2014-11-10 15:58:38 -0800710
711 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
712 return true;
713 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
714 return true;
715
716 LOG(ERROR) << "Unable to determine file system type.";
717 return false;
718}
719
720bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
721 int* out_block_count,
722 int* out_block_size) {
723 // See include/linux/ext2_fs.h for more details on the structure. We obtain
724 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
725 // library.
726 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
727 return false;
728
729 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
730
731 // ext3_fs.h: ext3_super_block.s_blocks_count
732 uint32_t block_count =
733 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
734
735 // ext3_fs.h: ext3_super_block.s_log_block_size
736 uint32_t log_block_size =
737 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
738
739 // ext3_fs.h: ext3_super_block.s_magic
740 uint16_t magic =
741 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
742
Darin Petkovd3f8c892010-10-12 21:38:45 -0700743 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800744 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700745 magic = le16toh(magic);
746
747 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800748 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
749 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
750 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700751 TEST_AND_RETURN_FALSE(block_count > 0);
752
Alex Deymo192393b2014-11-10 15:58:38 -0800753 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700754 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800755 if (out_block_size)
756 *out_block_size = 1 << log_block_size;
757 return true;
758}
759
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800760bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800761 int* out_block_count,
762 int* out_block_size) {
763 // See fs/squashfs/squashfs_fs.h for format details. We only support
764 // Squashfs 4.x little endian.
765
766 // sizeof(struct squashfs_super_block)
767 const size_t kSquashfsSuperBlockSize = 96;
768 if (buffer_size < kSquashfsSuperBlockSize)
769 return false;
770
771 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
772 if (memcmp(buffer, "hsqs", 4) != 0)
773 return false; // Only little endian is supported.
774
775 // squashfs_fs.h: struct squashfs_super_block.s_major
776 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
777 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
778
779 if (s_major != 4) {
780 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
781 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700782 }
Alex Deymo192393b2014-11-10 15:58:38 -0800783
784 // squashfs_fs.h: struct squashfs_super_block.bytes_used
785 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
786 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
787
788 const int block_size = 4096;
789
790 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
791 // so we round up to the nearest blocksize.
792 if (out_block_count)
793 *out_block_count = (bytes_used + block_size - 1) / block_size;
794 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700795 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700796 return true;
797}
798
Alex Deymo60ca1a72015-06-18 18:19:15 -0700799bool IsExtFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700800 chromeos::Blob header;
801 // The first 2 KiB is enough to read the ext2 superblock (located at offset
802 // 1024).
803 if (!ReadFileChunk(device, 0, 2048, &header))
804 return false;
805 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
806}
807
Alex Deymo60ca1a72015-06-18 18:19:15 -0700808bool IsSquashfsFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700809 chromeos::Blob header;
810 // The first 96 is enough to read the squashfs superblock.
811 const ssize_t kSquashfsSuperBlockSize = 96;
812 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
813 return false;
814 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
815}
816
Alex Deymo032e7722014-03-25 17:53:56 -0700817// Tries to parse the header of an ELF file to obtain a human-readable
818// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800819static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
820 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700821 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700822 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700823 return false;
824 *output = "ELF";
825
826 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700827 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700828 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700829 switch (buffer[EI_CLASS]) {
830 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700831 *output += " 32-bit";
832 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700833 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700834 *output += " 64-bit";
835 break;
836 default:
837 *output += " ?-bit";
838 }
839
840 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700841 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700842 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800843 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700844 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700845 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700846 *output += " little-endian";
847 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700848 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700849 *output += " big-endian";
850 break;
851 default:
852 *output += " ?-endian";
853 // Don't parse anything after the 0x10 offset if endianness is unknown.
854 return true;
855 }
856
Alex Deymoc1711e22014-08-08 13:16:23 -0700857 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
858 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
859 // and size is the same for both 32 and 64 bits.
860 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700861 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700862 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700863 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700864 if (ei_data == ELFDATA2LSB)
865 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700866 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700867 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700868
869 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700870 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700871 *output += " x86";
872 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700873 case EM_MIPS:
874 *output += " mips";
875 break;
876 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700877 *output += " arm";
878 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700879 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700880 *output += " x86-64";
881 break;
882 default:
883 *output += " unknown-arch";
884 }
885 return true;
886}
887
888string GetFileFormat(const string& path) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800889 chromeos::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700890 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
891 return "File not found.";
892
893 string result;
894 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
895 return result;
896
897 return "data";
898}
899
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800900namespace {
901// Do the actual trigger. We do it as a main-loop callback to (try to) get a
902// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700903void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800904 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700905 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800906 if (pid == 0) {
907 // We are the child. Crash.
908 abort(); // never returns
909 }
910 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700911 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800912 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800913}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700914} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800915
916void ScheduleCrashReporterUpload() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700917 chromeos::MessageLoop::current()->PostTask(
918 FROM_HERE,
919 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800920}
921
Chris Sosa4f8ee272012-11-30 13:01:54 -0800922bool SetCpuShares(CpuShares shares) {
923 string string_shares = base::IntToString(static_cast<int>(shares));
924 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
925 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700926 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
927 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800928 return true;
929 } else {
930 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
931 << " using " << cpu_shares_file;
932 return false;
933 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700934}
935
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700936int FuzzInt(int value, unsigned int range) {
937 int min = value - range / 2;
938 int max = value + range - range / 2;
939 return base::RandInt(min, max);
940}
941
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700942string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800943 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700944}
945
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800946string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400947 string str;
948
949 // Handle negative durations by prefixing with a minus.
950 if (delta.ToInternalValue() < 0) {
951 delta *= -1;
952 str = "-";
953 }
954
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700955 // Canonicalize into days, hours, minutes, seconds and microseconds.
956 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800957 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700958 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800959 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700960 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800961 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700962 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800963 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700964 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800965
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700966 if (days)
967 base::StringAppendF(&str, "%ud", days);
968 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800969 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700970 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800971 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700972 base::StringAppendF(&str, "%u", secs);
973 if (usecs) {
974 int width = 6;
975 while ((usecs / 10) * 10 == usecs) {
976 usecs /= 10;
977 width--;
978 }
979 base::StringAppendF(&str, ".%0*u", width, usecs);
980 }
981 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800982 return str;
983}
984
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700985string ToString(const Time utc_time) {
986 Time::Exploded exp_time;
987 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700988 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700989 exp_time.month,
990 exp_time.day_of_month,
991 exp_time.year,
992 exp_time.hour,
993 exp_time.minute,
994 exp_time.second);
995}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000996
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700997string ToString(bool b) {
998 return (b ? "true" : "false");
999}
1000
Alex Deymo1c656c42013-06-28 11:02:14 -07001001string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001002 switch (source) {
1003 case kDownloadSourceHttpsServer: return "HttpsServer";
1004 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -07001005 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -07001006 case kNumDownloadSources: return "Unknown";
1007 // Don't add a default case to let the compiler warn about newly added
1008 // download sources which should be added here.
1009 }
1010
1011 return "Unknown";
1012}
1013
Alex Deymo1c656c42013-06-28 11:02:14 -07001014string ToString(PayloadType payload_type) {
1015 switch (payload_type) {
1016 case kPayloadTypeDelta: return "Delta";
1017 case kPayloadTypeFull: return "Full";
1018 case kPayloadTypeForcedFull: return "ForcedFull";
1019 case kNumPayloadTypes: return "Unknown";
1020 // Don't add a default case to let the compiler warn about newly added
1021 // payload types which should be added here.
1022 }
1023
1024 return "Unknown";
1025}
1026
David Zeuthena99981f2013-04-29 13:42:47 -07001027ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001028 // Ignore the higher order bits in the code by applying the mask as
1029 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001030 // with values less than ErrorCode::kUmaReportedMax.
1031 ErrorCode base_code = static_cast<ErrorCode>(
1032 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -07001033
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001034 // Make additional adjustments required for UMA and error classification.
1035 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
1036 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001037 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001038 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001039 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001040 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001041 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1042 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001043 }
1044
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001045 return base_code;
1046}
1047
David Zeuthen33bae492014-02-25 16:16:18 -08001048metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001049 ErrorCode base_code = static_cast<ErrorCode>(
1050 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001051
1052 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001053 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001054 return metrics::AttemptResult::kUpdateSucceeded;
1055
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001056 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001057 return metrics::AttemptResult::kPayloadDownloadError;
1058
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001059 case ErrorCode::kDownloadInvalidMetadataSize:
1060 case ErrorCode::kDownloadInvalidMetadataMagicString:
1061 case ErrorCode::kDownloadMetadataSignatureError:
1062 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1063 case ErrorCode::kPayloadMismatchedType:
1064 case ErrorCode::kUnsupportedMajorPayloadVersion:
1065 case ErrorCode::kUnsupportedMinorPayloadVersion:
1066 case ErrorCode::kDownloadNewPartitionInfoError:
1067 case ErrorCode::kDownloadSignatureMissingInManifest:
1068 case ErrorCode::kDownloadManifestParseError:
1069 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001070 return metrics::AttemptResult::kMetadataMalformed;
1071
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001072 case ErrorCode::kDownloadOperationHashMismatch:
1073 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001074 return metrics::AttemptResult::kOperationMalformed;
1075
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001076 case ErrorCode::kDownloadOperationExecutionError:
1077 case ErrorCode::kInstallDeviceOpenError:
1078 case ErrorCode::kKernelDeviceOpenError:
1079 case ErrorCode::kDownloadWriteError:
1080 case ErrorCode::kFilesystemCopierError:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001081 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001082 return metrics::AttemptResult::kOperationExecutionError;
1083
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001084 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001085 return metrics::AttemptResult::kMetadataVerificationFailed;
1086
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001087 case ErrorCode::kPayloadSizeMismatchError:
1088 case ErrorCode::kPayloadHashMismatchError:
1089 case ErrorCode::kDownloadPayloadVerificationError:
1090 case ErrorCode::kSignedDeltaPayloadExpectedError:
1091 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001092 return metrics::AttemptResult::kPayloadVerificationFailed;
1093
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001094 case ErrorCode::kNewRootfsVerificationError:
1095 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001096 return metrics::AttemptResult::kVerificationFailed;
1097
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001098 case ErrorCode::kPostinstallRunnerError:
1099 case ErrorCode::kPostinstallBootedFromFirmwareB:
1100 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001101 return metrics::AttemptResult::kPostInstallFailed;
1102
1103 // We should never get these errors in the update-attempt stage so
1104 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001105 case ErrorCode::kError:
1106 case ErrorCode::kOmahaRequestXMLParseError:
1107 case ErrorCode::kOmahaRequestError:
1108 case ErrorCode::kOmahaResponseHandlerError:
1109 case ErrorCode::kDownloadStateInitializationError:
1110 case ErrorCode::kOmahaRequestEmptyResponseError:
1111 case ErrorCode::kDownloadInvalidMetadataSignature:
1112 case ErrorCode::kOmahaResponseInvalid:
1113 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1114 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1115 case ErrorCode::kOmahaErrorInHTTPResponse:
1116 case ErrorCode::kDownloadMetadataSignatureMissingError:
1117 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1118 case ErrorCode::kPostinstallPowerwashError:
1119 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001120 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001121 return metrics::AttemptResult::kInternalError;
1122
1123 // Special flags. These can't happen (we mask them out above) but
1124 // the compiler doesn't know that. Just break out so we can warn and
1125 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001126 case ErrorCode::kUmaReportedMax:
1127 case ErrorCode::kOmahaRequestHTTPResponseBase:
1128 case ErrorCode::kDevModeFlag:
1129 case ErrorCode::kResumedFlag:
1130 case ErrorCode::kTestImageFlag:
1131 case ErrorCode::kTestOmahaUrlFlag:
1132 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001133 break;
1134 }
1135
1136 LOG(ERROR) << "Unexpected error code " << base_code;
1137 return metrics::AttemptResult::kInternalError;
1138}
1139
1140
1141metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001142 ErrorCode base_code = static_cast<ErrorCode>(
1143 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001144
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001145 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1146 int http_status =
1147 static_cast<int>(base_code) -
1148 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001149 if (http_status >= 200 && http_status <= 599) {
1150 return static_cast<metrics::DownloadErrorCode>(
1151 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1152 http_status - 200);
1153 } else if (http_status == 0) {
1154 // The code is using HTTP Status 0 for "Unable to get http
1155 // response code."
1156 return metrics::DownloadErrorCode::kDownloadError;
1157 }
1158 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1159 return metrics::DownloadErrorCode::kHttpStatusOther;
1160 }
1161
1162 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001163 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001164 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1165 //
1166 // For now just map that to kDownloading. See http://crbug.com/355745
1167 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001168 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001169 return metrics::DownloadErrorCode::kDownloadError;
1170
1171 // All of these error codes are not related to downloading so break
1172 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001173 case ErrorCode::kSuccess:
1174 case ErrorCode::kError:
1175 case ErrorCode::kOmahaRequestError:
1176 case ErrorCode::kOmahaResponseHandlerError:
1177 case ErrorCode::kFilesystemCopierError:
1178 case ErrorCode::kPostinstallRunnerError:
1179 case ErrorCode::kPayloadMismatchedType:
1180 case ErrorCode::kInstallDeviceOpenError:
1181 case ErrorCode::kKernelDeviceOpenError:
1182 case ErrorCode::kPayloadHashMismatchError:
1183 case ErrorCode::kPayloadSizeMismatchError:
1184 case ErrorCode::kDownloadPayloadVerificationError:
1185 case ErrorCode::kDownloadNewPartitionInfoError:
1186 case ErrorCode::kDownloadWriteError:
1187 case ErrorCode::kNewRootfsVerificationError:
1188 case ErrorCode::kNewKernelVerificationError:
1189 case ErrorCode::kSignedDeltaPayloadExpectedError:
1190 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1191 case ErrorCode::kPostinstallBootedFromFirmwareB:
1192 case ErrorCode::kDownloadStateInitializationError:
1193 case ErrorCode::kDownloadInvalidMetadataMagicString:
1194 case ErrorCode::kDownloadSignatureMissingInManifest:
1195 case ErrorCode::kDownloadManifestParseError:
1196 case ErrorCode::kDownloadMetadataSignatureError:
1197 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1198 case ErrorCode::kDownloadMetadataSignatureMismatch:
1199 case ErrorCode::kDownloadOperationHashVerificationError:
1200 case ErrorCode::kDownloadOperationExecutionError:
1201 case ErrorCode::kDownloadOperationHashMismatch:
1202 case ErrorCode::kOmahaRequestEmptyResponseError:
1203 case ErrorCode::kOmahaRequestXMLParseError:
1204 case ErrorCode::kDownloadInvalidMetadataSize:
1205 case ErrorCode::kDownloadInvalidMetadataSignature:
1206 case ErrorCode::kOmahaResponseInvalid:
1207 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1208 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1209 case ErrorCode::kOmahaErrorInHTTPResponse:
1210 case ErrorCode::kDownloadOperationHashMissingError:
1211 case ErrorCode::kDownloadMetadataSignatureMissingError:
1212 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1213 case ErrorCode::kPostinstallPowerwashError:
1214 case ErrorCode::kUpdateCanceledByChannelChange:
1215 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1216 case ErrorCode::kUnsupportedMajorPayloadVersion:
1217 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001218 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001219 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001220 break;
1221
1222 // Special flags. These can't happen (we mask them out above) but
1223 // the compiler doesn't know that. Just break out so we can warn and
1224 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001225 case ErrorCode::kUmaReportedMax:
1226 case ErrorCode::kOmahaRequestHTTPResponseBase:
1227 case ErrorCode::kDevModeFlag:
1228 case ErrorCode::kResumedFlag:
1229 case ErrorCode::kTestImageFlag:
1230 case ErrorCode::kTestOmahaUrlFlag:
1231 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001232 LOG(ERROR) << "Unexpected error code " << base_code;
1233 break;
1234 }
1235
1236 return metrics::DownloadErrorCode::kInputMalformed;
1237}
1238
David Zeuthenb281f072014-04-02 10:20:19 -07001239metrics::ConnectionType GetConnectionType(
1240 NetworkConnectionType type,
1241 NetworkTethering tethering) {
1242 switch (type) {
1243 case kNetUnknown:
1244 return metrics::ConnectionType::kUnknown;
1245
1246 case kNetEthernet:
1247 if (tethering == NetworkTethering::kConfirmed)
1248 return metrics::ConnectionType::kTetheredEthernet;
1249 else
1250 return metrics::ConnectionType::kEthernet;
1251
1252 case kNetWifi:
1253 if (tethering == NetworkTethering::kConfirmed)
1254 return metrics::ConnectionType::kTetheredWifi;
1255 else
1256 return metrics::ConnectionType::kWifi;
1257
1258 case kNetWimax:
1259 return metrics::ConnectionType::kWimax;
1260
1261 case kNetBluetooth:
1262 return metrics::ConnectionType::kBluetooth;
1263
1264 case kNetCellular:
1265 return metrics::ConnectionType::kCellular;
1266 }
1267
1268 LOG(ERROR) << "Unexpected network connection type: type=" << type
1269 << ", tethering=" << static_cast<int>(tethering);
1270
1271 return metrics::ConnectionType::kUnknown;
1272}
1273
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001274// Returns a printable version of the various flags denoted in the higher order
1275// bits of the given code. Returns an empty string if none of those bits are
1276// set.
1277string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001278 uint32_t flags = (static_cast<uint32_t>(code) &
1279 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001280 string flag_names;
1281 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001282 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001283 uint32_t flag = flags & (1 << i);
1284 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001285 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001286 separator = ", ";
1287 }
1288 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001289
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001290 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001291}
1292
David Zeuthena99981f2013-04-29 13:42:47 -07001293void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001294 if (!system_state)
1295 return;
1296
David Zeuthena99981f2013-04-29 13:42:47 -07001297 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001298
1299 // If the code doesn't have flags computed already, compute them now based on
1300 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001301 uint32_t flags =
1302 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001303 if (!flags)
1304 flags = system_state->update_attempter()->GetErrorCodeFlags();
1305
1306 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1307 // flag, as it's perfectly normal for production devices to resume their
1308 // downloads and so we want to record those cases also in NormalErrorCodes
1309 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001310 string metric =
1311 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001312 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1313
1314 LOG(INFO) << "Sending error code " << uma_error_code
1315 << " (" << CodeToString(uma_error_code) << ")"
1316 << " to UMA metric: " << metric
1317 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1318
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001319 system_state->metrics_lib()->SendEnumToUMA(
1320 metric, static_cast<int>(uma_error_code),
1321 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001322}
1323
David Zeuthena99981f2013-04-29 13:42:47 -07001324string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001325 // If the given code has both parts (i.e. the error code part and the flags
1326 // part) then strip off the flags part since the switch statement below
1327 // has case statements only for the base error code or a single flag but
1328 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001329 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1330 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1331 code = static_cast<ErrorCode>(
1332 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001333 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001334 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1335 case ErrorCode::kError: return "ErrorCode::kError";
1336 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1337 case ErrorCode::kOmahaResponseHandlerError:
1338 return "ErrorCode::kOmahaResponseHandlerError";
1339 case ErrorCode::kFilesystemCopierError:
1340 return "ErrorCode::kFilesystemCopierError";
1341 case ErrorCode::kPostinstallRunnerError:
1342 return "ErrorCode::kPostinstallRunnerError";
1343 case ErrorCode::kPayloadMismatchedType:
1344 return "ErrorCode::kPayloadMismatchedType";
1345 case ErrorCode::kInstallDeviceOpenError:
1346 return "ErrorCode::kInstallDeviceOpenError";
1347 case ErrorCode::kKernelDeviceOpenError:
1348 return "ErrorCode::kKernelDeviceOpenError";
1349 case ErrorCode::kDownloadTransferError:
1350 return "ErrorCode::kDownloadTransferError";
1351 case ErrorCode::kPayloadHashMismatchError:
1352 return "ErrorCode::kPayloadHashMismatchError";
1353 case ErrorCode::kPayloadSizeMismatchError:
1354 return "ErrorCode::kPayloadSizeMismatchError";
1355 case ErrorCode::kDownloadPayloadVerificationError:
1356 return "ErrorCode::kDownloadPayloadVerificationError";
1357 case ErrorCode::kDownloadNewPartitionInfoError:
1358 return "ErrorCode::kDownloadNewPartitionInfoError";
1359 case ErrorCode::kDownloadWriteError:
1360 return "ErrorCode::kDownloadWriteError";
1361 case ErrorCode::kNewRootfsVerificationError:
1362 return "ErrorCode::kNewRootfsVerificationError";
1363 case ErrorCode::kNewKernelVerificationError:
1364 return "ErrorCode::kNewKernelVerificationError";
1365 case ErrorCode::kSignedDeltaPayloadExpectedError:
1366 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1367 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1368 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1369 case ErrorCode::kPostinstallBootedFromFirmwareB:
1370 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1371 case ErrorCode::kDownloadStateInitializationError:
1372 return "ErrorCode::kDownloadStateInitializationError";
1373 case ErrorCode::kDownloadInvalidMetadataMagicString:
1374 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1375 case ErrorCode::kDownloadSignatureMissingInManifest:
1376 return "ErrorCode::kDownloadSignatureMissingInManifest";
1377 case ErrorCode::kDownloadManifestParseError:
1378 return "ErrorCode::kDownloadManifestParseError";
1379 case ErrorCode::kDownloadMetadataSignatureError:
1380 return "ErrorCode::kDownloadMetadataSignatureError";
1381 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1382 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1383 case ErrorCode::kDownloadMetadataSignatureMismatch:
1384 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1385 case ErrorCode::kDownloadOperationHashVerificationError:
1386 return "ErrorCode::kDownloadOperationHashVerificationError";
1387 case ErrorCode::kDownloadOperationExecutionError:
1388 return "ErrorCode::kDownloadOperationExecutionError";
1389 case ErrorCode::kDownloadOperationHashMismatch:
1390 return "ErrorCode::kDownloadOperationHashMismatch";
1391 case ErrorCode::kOmahaRequestEmptyResponseError:
1392 return "ErrorCode::kOmahaRequestEmptyResponseError";
1393 case ErrorCode::kOmahaRequestXMLParseError:
1394 return "ErrorCode::kOmahaRequestXMLParseError";
1395 case ErrorCode::kDownloadInvalidMetadataSize:
1396 return "ErrorCode::kDownloadInvalidMetadataSize";
1397 case ErrorCode::kDownloadInvalidMetadataSignature:
1398 return "ErrorCode::kDownloadInvalidMetadataSignature";
1399 case ErrorCode::kOmahaResponseInvalid:
1400 return "ErrorCode::kOmahaResponseInvalid";
1401 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1402 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1403 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1404 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1405 case ErrorCode::kOmahaErrorInHTTPResponse:
1406 return "ErrorCode::kOmahaErrorInHTTPResponse";
1407 case ErrorCode::kDownloadOperationHashMissingError:
1408 return "ErrorCode::kDownloadOperationHashMissingError";
1409 case ErrorCode::kDownloadMetadataSignatureMissingError:
1410 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1411 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1412 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1413 case ErrorCode::kPostinstallPowerwashError:
1414 return "ErrorCode::kPostinstallPowerwashError";
1415 case ErrorCode::kUpdateCanceledByChannelChange:
1416 return "ErrorCode::kUpdateCanceledByChannelChange";
1417 case ErrorCode::kUmaReportedMax:
1418 return "ErrorCode::kUmaReportedMax";
1419 case ErrorCode::kOmahaRequestHTTPResponseBase:
1420 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1421 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001422 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001423 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001424 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001425 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001426 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001427 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001428 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001429 case ErrorCode::kSpecialFlags:
1430 return "ErrorCode::kSpecialFlags";
1431 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1432 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1433 case ErrorCode::kUnsupportedMajorPayloadVersion:
1434 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1435 case ErrorCode::kUnsupportedMinorPayloadVersion:
1436 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001437 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1438 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Allie Woodeb9e6d82015-04-17 13:55:30 -07001439 case ErrorCode::kFilesystemVerifierError:
1440 return "ErrorCode::kFilesystemVerifierError";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001441 // Don't add a default case to let the compiler warn about newly added
1442 // error codes which should be added here.
1443 }
1444
1445 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1446}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001447
Gilad Arnold30dedd82013-07-03 06:19:09 -07001448bool CreatePowerwashMarkerFile(const char* file_path) {
1449 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1450 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001451 kPowerwashCommand,
1452 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001453 if (result) {
1454 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1455 } else {
1456 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1457 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001458
1459 return result;
1460}
1461
Gilad Arnold30dedd82013-07-03 06:19:09 -07001462bool DeletePowerwashMarkerFile(const char* file_path) {
1463 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001464 const base::FilePath kPowerwashMarkerPath(marker_file);
1465 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001466
1467 if (result)
1468 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001469 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001470 else
1471 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001472 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001473
1474 return result;
1475}
1476
Alex Deymof329b932014-10-30 01:37:48 -07001477bool GetInstallDev(const string& boot_dev, string* install_dev) {
1478 string disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001479 int partition_num;
1480 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1481 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001482
Chris Sosad317e402013-06-12 13:47:09 -07001483 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001484 if (partition_num == 3) {
1485 partition_num = 5;
1486 } else if (partition_num == 5) {
1487 partition_num = 3;
1488 } else {
1489 return false;
1490 }
1491
1492 if (install_dev)
1493 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001494
Chris Sosad317e402013-06-12 13:47:09 -07001495 return true;
1496}
1497
David Zeuthen27a48bc2013-08-06 12:06:29 -07001498Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001499 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1500 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001501 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1502}
1503
Alex Deymof329b932014-10-30 01:37:48 -07001504string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001505 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001506 for (vector<string>::const_iterator i = vec_str.begin();
1507 i != vec_str.end(); ++i) {
1508 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001509 str += ", ";
1510 str += '"';
1511 str += *i;
1512 str += '"';
1513 }
1514 str += "]";
1515 return str;
1516}
1517
David Zeuthen8f191b22013-08-06 12:27:50 -07001518string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001519 string encoded_hash = chromeos::data_encoding::Base64Encode(payload_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001520 return base::StringPrintf("cros_update_size_%zu_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001521 payload_size,
1522 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001523}
1524
Alex Deymof329b932014-10-30 01:37:48 -07001525bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001526 base::FilePath *out_path) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001527 chromeos::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001528
1529 out_path->clear();
1530
1531 if (base64_encoded.size() == 0) {
1532 LOG(ERROR) << "Can't decode empty string.";
1533 return false;
1534 }
1535
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001536 if (!chromeos::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001537 contents.size() == 0) {
1538 LOG(ERROR) << "Error decoding base64.";
1539 return false;
1540 }
1541
Alex Vakulenko75039d72014-03-25 12:36:28 -07001542 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001543 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001544 LOG(ERROR) << "Error creating temporary file.";
1545 return false;
1546 }
1547
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001548 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001549 PLOG(ERROR) << "Error writing to temporary file.";
1550 if (fclose(file) != 0)
1551 PLOG(ERROR) << "Error closing temporary file.";
1552 if (unlink(out_path->value().c_str()) != 0)
1553 PLOG(ERROR) << "Error unlinking temporary file.";
1554 out_path->clear();
1555 return false;
1556 }
1557
1558 if (fclose(file) != 0) {
1559 PLOG(ERROR) << "Error closing temporary file.";
1560 out_path->clear();
1561 return false;
1562 }
1563
1564 return true;
1565}
1566
Alex Deymof329b932014-10-30 01:37:48 -07001567bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001568 time_t unix_time = time.ToTimeT();
1569 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1570 const time_t kOmahaEpoch = 1167638400;
1571 const int64_t kNumSecondsPerWeek = 7*24*3600;
1572 const int64_t kNumDaysPerWeek = 7;
1573
1574 time_t omaha_time = unix_time - kOmahaEpoch;
1575
1576 if (omaha_time < 0)
1577 return false;
1578
1579 // Note, as per the comment in utils.h we are deliberately not
1580 // handling DST correctly.
1581
1582 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1583 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1584
1585 return true;
1586}
1587
David Zeuthen33bae492014-02-25 16:16:18 -08001588bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001589 const string& state_variable_key,
1590 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001591 bool ret = false;
1592
Alex Deymof329b932014-10-30 01:37:48 -07001593 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001594 int64_t stored_value;
1595 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001596 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001597 if (stored_time > now) {
1598 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1599 << " is in the future.";
1600 } else {
1601 *out_duration = now - stored_time;
1602 ret = true;
1603 }
1604 }
1605
1606 if (!system_state->prefs()->SetInt64(state_variable_key,
1607 now.ToInternalValue())) {
1608 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1609 }
1610
1611 return ret;
1612}
1613
1614bool MonotonicDurationHelper(SystemState* system_state,
1615 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001616 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001617 bool ret = false;
1618
Alex Deymof329b932014-10-30 01:37:48 -07001619 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001620 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001621 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001622 *out_duration = now - stored_time;
1623 ret = true;
1624 }
1625 *storage = now.ToInternalValue();
1626
1627 return ret;
1628}
1629
Alex Deymob42b98d2015-07-06 17:42:38 -07001630bool GetMinorVersion(const chromeos::KeyValueStore& store,
1631 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001632 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001633 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001634 if (!base::StringToUint(result, minor_version)) {
1635 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1636 return false;
1637 }
Allie Wood78750a42015-02-11 15:42:11 -08001638 return true;
1639 }
1640 return false;
1641}
1642
Alex Deymo60ca1a72015-06-18 18:19:15 -07001643bool ReadExtents(const string& path, const vector<Extent>& extents,
Allie Wood56873452015-03-27 17:48:40 -07001644 chromeos::Blob* out_data, ssize_t out_data_size,
1645 size_t block_size) {
1646 chromeos::Blob data(out_data_size);
1647 ssize_t bytes_read = 0;
1648 int fd = open(path.c_str(), O_RDONLY);
1649 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1650 ScopedFdCloser fd_closer(&fd);
1651
Gilad Arnold41e34742015-05-11 11:31:50 -07001652 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001653 ssize_t bytes_read_this_iteration = 0;
1654 ssize_t bytes = extent.num_blocks() * block_size;
1655 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1656 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1657 &data[bytes_read],
1658 bytes,
1659 extent.start_block() * block_size,
1660 &bytes_read_this_iteration));
1661 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1662 bytes_read += bytes_read_this_iteration;
1663 }
1664 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1665 *out_data = data;
1666 return true;
1667}
1668
adlr@google.com3defe6a2009-12-04 20:57:17 +00001669} // namespace utils
1670
1671} // namespace chromeos_update_engine