blob: 03f642abee99d58b0cfbc75cc5ae1d9a9c019fed [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>
Allie Wood78750a42015-02-11 15:42:11 -080041#include <chromeos/key_value_store.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070042#include <chromeos/message_loops/message_loop.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080043#include <glib.h>
Will Drewry8f71da82010-08-30 14:07:11 -050044
David Zeuthen33bae492014-02-25 16:16:18 -080045#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070046#include "update_engine/constants.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080047#include "update_engine/file_descriptor.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080048#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070049#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080050#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070051#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080052#include "update_engine/system_state.h"
53#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000054
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070055using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080056using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000057using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070058using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000059using std::string;
60using std::vector;
61
62namespace chromeos_update_engine {
63
Ben Chan77a1eba2012-10-07 22:54:55 -070064namespace {
65
66// The following constants control how UnmountFilesystem should retry if
67// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
68// one second.
69const int kUnmountMaxNumOfRetries = 5;
70const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070071
72// Number of bytes to read from a file to attempt to detect its contents. Used
73// in GetFileFormat.
74const int kGetFileFormatMaxHeaderSize = 32;
75
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080076// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
77// simply based on the name of the device.
78bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070079 return base::StartsWithASCII(disk_name, "/dev/ubi", true) ||
80 base::StartsWithASCII(disk_name, "/dev/mtd", true);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080081}
82
83// Return the device name for the corresponding partition on a NAND device.
84// WARNING: This function returns device names that are not mountable.
85string MakeNandPartitionName(int partition_num) {
86 switch (partition_num) {
87 case 2:
88 case 4:
89 case 6: {
90 return base::StringPrintf("/dev/mtd%d", partition_num);
91 }
92 default: {
93 return base::StringPrintf("/dev/ubi%d_0", partition_num);
94 }
95 }
96}
97
98// Return the device name for the corresponding partition on a NAND device that
99// may be mountable (but may not be writable).
100string MakeNandPartitionNameForMount(int partition_num) {
101 switch (partition_num) {
102 case 2:
103 case 4:
104 case 6: {
105 return base::StringPrintf("/dev/mtd%d", partition_num);
106 }
107 case 3:
108 case 5:
109 case 7: {
110 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
111 }
112 default: {
113 return base::StringPrintf("/dev/ubi%d_0", partition_num);
114 }
115 }
116}
117
Ben Chan77a1eba2012-10-07 22:54:55 -0700118} // namespace
119
adlr@google.com3defe6a2009-12-04 20:57:17 +0000120namespace utils {
121
Chris Sosa4f8ee272012-11-30 13:01:54 -0800122// Cgroup container is created in update-engine's upstart script located at
123// /etc/init/update-engine.conf.
124static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
125
J. Richard Barnette63137e52013-10-28 10:57:29 -0700126string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700127 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700128
Alex Vakulenko75039d72014-03-25 12:36:28 -0700129 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700130 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700131 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700132 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800133 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700134 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800135 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700136 string output;
137 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800138 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700139 return output;
140 }
141 }
142 }
143 LOG(ERROR) << "Unable to parse fwid from ec info.";
144 return "";
145}
146
147
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700148const string KernelDeviceOfBootDevice(const string& boot_device) {
149 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700150
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700151 string disk_name;
152 int partition_num;
153 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700154 // Currently this assumes the partition number of the boot device is
155 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
156 // get the kernel device.
157 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
158 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
159 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700160 }
161
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700162 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700163}
164
165
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800166bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800167 DirectFileWriter writer;
168 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
169 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700170 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800171 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800172 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800173 return true;
174}
175
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700176bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700177 const char* c_buf = static_cast<const char*>(buf);
178 ssize_t bytes_written = 0;
179 while (bytes_written < static_cast<ssize_t>(count)) {
180 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
181 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
182 bytes_written += rc;
183 }
184 return true;
185}
186
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700187bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
188 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700189 size_t bytes_written = 0;
190 int num_attempts = 0;
191 while (bytes_written < count) {
192 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700193 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
194 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700195 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
196 if (rc < 0) {
197 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
198 << " bytes_written=" << bytes_written
199 << " count=" << count << " offset=" << offset;
200 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700201 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
202 bytes_written += rc;
203 }
204 return true;
205}
206
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800207bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
208 const char* c_buf = static_cast<const char*>(buf);
209 ssize_t bytes_written = 0;
210 while (bytes_written < static_cast<ssize_t>(count)) {
211 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
212 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
213 bytes_written += rc;
214 }
215 return true;
216}
217
218bool PWriteAll(FileDescriptorPtr fd,
219 const void* buf,
220 size_t count,
221 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700222 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
223 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800224 return WriteAll(fd, buf, count);
225}
226
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700227bool PReadAll(int fd, void* buf, size_t count, off_t offset,
228 ssize_t* out_bytes_read) {
229 char* c_buf = static_cast<char*>(buf);
230 ssize_t bytes_read = 0;
231 while (bytes_read < static_cast<ssize_t>(count)) {
232 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
233 offset + bytes_read);
234 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
235 if (rc == 0) {
236 break;
237 }
238 bytes_read += rc;
239 }
240 *out_bytes_read = bytes_read;
241 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700242}
243
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800244bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
245 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700246 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
247 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800248 char* c_buf = static_cast<char*>(buf);
249 ssize_t bytes_read = 0;
250 while (bytes_read < static_cast<ssize_t>(count)) {
251 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
252 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
253 if (rc == 0) {
254 break;
255 }
256 bytes_read += rc;
257 }
258 *out_bytes_read = bytes_read;
259 return true;
260}
261
Gilad Arnold19a45f02012-07-19 12:36:10 -0700262// Append |nbytes| of content from |buf| to the vector pointed to by either
263// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800264static void AppendBytes(const uint8_t* buf, size_t nbytes,
265 chromeos::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700266 CHECK(buf);
267 CHECK(vec_p);
268 vec_p->insert(vec_p->end(), buf, buf + nbytes);
269}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800270static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700271 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700272 CHECK(buf);
273 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800274 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700275}
276
277// Reads from an open file |fp|, appending the read content to the container
278// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200279// file's content, false otherwise. If |size| is not -1, reads up to |size|
280// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700281template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200282static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700283 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200284 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800285 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200286 while (size == -1 || size > 0) {
287 off_t bytes_to_read = sizeof(buf);
288 if (size > 0 && bytes_to_read > size) {
289 bytes_to_read = size;
290 }
291 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
292 if (!nbytes) {
293 break;
294 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700295 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200296 if (size != -1) {
297 CHECK(size >= static_cast<off_t>(nbytes));
298 size -= nbytes;
299 }
300 }
301 if (ferror(fp)) {
302 return false;
303 }
304 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700305}
306
Darin Petkov8e447e02013-04-16 16:23:50 +0200307// Opens a file |path| for reading and appends its the contents to a container
308// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
309// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700310template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700311static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200312 off_t offset,
313 off_t size,
314 T* out_p) {
315 CHECK_GE(offset, 0);
316 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700317 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200318 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000319 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200320 if (offset) {
321 // Return success without appending any data if a chunk beyond the end of
322 // the file is requested.
323 if (offset >= FileSize(path)) {
324 return true;
325 }
326 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
327 }
328 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000329}
330
Alex Deymo10875d92014-11-10 21:52:57 -0800331// TODO(deymo): This is only used in unittest, but requires the private
332// Read<string>() defined here. Expose Read<string>() or move to base/ version.
333bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700334 FILE* fp = popen(cmd.c_str(), "r");
335 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000336 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200337 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700338 return (success && pclose(fp) >= 0);
339}
340
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800341bool ReadFile(const string& path, chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200342 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700343}
344
Darin Petkov8e447e02013-04-16 16:23:50 +0200345bool ReadFile(const string& path, string* out_p) {
346 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700347}
348
Darin Petkov8e447e02013-04-16 16:23:50 +0200349bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800350 chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200351 return ReadFileChunkAndAppend(path, offset, size, out_p);
352}
353
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700354off_t BlockDevSize(int fd) {
355 uint64_t dev_size;
356 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
357 if (rc == -1) {
358 dev_size = -1;
359 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
360 }
361 return dev_size;
362}
363
364off_t BlockDevSize(const string& path) {
365 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
366 if (fd == -1) {
367 PLOG(ERROR) << "Error opening " << path;
368 return fd;
369 }
370
371 off_t dev_size = BlockDevSize(fd);
372 if (dev_size == -1)
373 PLOG(ERROR) << "Error getting block device size on " << path;
374
375 close(fd);
376 return dev_size;
377}
378
379off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700380 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700381 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700382 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700383 if (rc < 0) {
384 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700385 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700386 }
387 if (S_ISREG(stbuf.st_mode))
388 return stbuf.st_size;
389 if (S_ISBLK(stbuf.st_mode))
390 return BlockDevSize(fd);
391 LOG(ERROR) << "Couldn't determine the type of " << fd;
392 return -1;
393}
394
395off_t FileSize(const string& path) {
396 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
397 if (fd == -1) {
398 PLOG(ERROR) << "Error opening " << path;
399 return fd;
400 }
401 off_t size = FileSize(fd);
402 if (size == -1)
403 PLOG(ERROR) << "Error getting file size of " << path;
404 close(fd);
405 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700406}
407
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800408void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000409 LOG(INFO) << "Logging array of length: " << length;
410 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700411 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000412 const unsigned int bytes_remaining = length - i;
413 const unsigned int bytes_per_this_line = min(bytes_per_line,
414 bytes_remaining);
415 char header[100];
416 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
417 TEST_AND_RETURN(r == 13);
418 string line = header;
419 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
420 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800421 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000422 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
423 TEST_AND_RETURN(r == 3);
424 line += buf;
425 }
426 LOG(INFO) << line;
427 }
428}
429
Alex Deymof329b932014-10-30 01:37:48 -0700430string GetDiskName(const string& partition_name) {
431 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800432 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700433 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700434}
435
Alex Deymof329b932014-10-30 01:37:48 -0700436int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800437 int partition_num = 0;
438 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
439 partition_num : 0;
440}
441
Alex Deymof329b932014-10-30 01:37:48 -0700442bool SplitPartitionName(const string& partition_name,
443 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800444 int* out_partition_num) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700445 if (!base::StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800446 LOG(ERROR) << "Invalid partition device name: " << partition_name;
447 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700448 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800449
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700450 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
451 if (last_nondigit_pos == string::npos ||
452 (last_nondigit_pos + 1) == partition_name.size()) {
453 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800454 return false;
455 }
456
Alex Deymof329b932014-10-30 01:37:48 -0700457 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700458 if (partition_name[last_nondigit_pos] == '_') {
459 // NAND block devices have weird naming which could be something
460 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
461 size_t prev_nondigit_pos =
462 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
463 if (prev_nondigit_pos == string::npos ||
464 (prev_nondigit_pos + 1) == last_nondigit_pos) {
465 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
466 return false;
467 }
468
469 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
470 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800471 }
472
473 if (out_disk_name) {
474 // Special case for MMC devices which have the following naming scheme:
475 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700476 size_t disk_name_len = last_nondigit_pos;
477 if (partition_name[last_nondigit_pos] != 'p' ||
478 last_nondigit_pos == 0 ||
479 !isdigit(partition_name[last_nondigit_pos - 1])) {
480 disk_name_len++;
481 }
482 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800483 }
484
485 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700486 string partition_str = partition_name.substr(last_nondigit_pos + 1,
487 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800488 *out_partition_num = atoi(partition_str.c_str());
489 }
490 return true;
491}
492
Alex Deymof329b932014-10-30 01:37:48 -0700493string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800494 if (partition_num < 1) {
495 LOG(ERROR) << "Invalid partition number: " << partition_num;
496 return string();
497 }
498
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700499 if (!base::StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800500 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700501 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800502 }
503
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800504 if (IsMtdDeviceName(disk_name)) {
505 // Special case for UBI block devices.
506 // 1. ubiblock is not writable, we need to use plain "ubi".
507 // 2. There is a "_0" suffix.
508 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800509 }
510
Alex Deymof329b932014-10-30 01:37:48 -0700511 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700512 if (isdigit(partition_name.back())) {
513 // Special case for devices with names ending with a digit.
514 // Add "p" to separate the disk name from partition number,
515 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800516 partition_name += 'p';
517 }
518
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700519 partition_name += std::to_string(partition_num);
520
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800521 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700522}
523
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800524string MakePartitionNameForMount(const string& part_name) {
525 if (IsMtdDeviceName(part_name)) {
526 int partition_num;
527 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
528 return "";
529 }
530 return MakeNandPartitionNameForMount(partition_num);
531 }
532 return part_name;
533}
534
Darin Petkovf74eb652010-08-04 12:08:38 -0700535string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700536 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700537 if (device_path.DirName().value() != "/dev") {
538 return "";
539 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700540 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700541}
542
Alex Deymof329b932014-10-30 01:37:48 -0700543bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700544 string sysfs_block = SysfsBlockDevice(device);
545 string removable;
546 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700547 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700548 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700549 return false;
550 }
Ben Chan736fcb52014-05-21 18:28:22 -0700551 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700552 return removable == "1";
553}
554
Alex Deymof329b932014-10-30 01:37:48 -0700555string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000556 char buf[100];
557 buf[0] = '\0';
558 return strerror_r(err, buf, sizeof(buf));
559}
560
adlr@google.com3defe6a2009-12-04 20:57:17 +0000561bool FileExists(const char* path) {
562 struct stat stbuf;
563 return 0 == lstat(path, &stbuf);
564}
565
Darin Petkov30291ed2010-11-12 10:23:06 -0800566bool IsSymlink(const char* path) {
567 struct stat stbuf;
568 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
569}
570
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800571bool TryAttachingUbiVolume(int volume_num, int timeout) {
572 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
573 if (FileExists(volume_path.c_str())) {
574 return true;
575 }
576
577 int exit_code;
578 vector<string> cmd = {
579 "ubiattach",
580 "-m",
581 base::StringPrintf("%d", volume_num),
582 "-d",
583 base::StringPrintf("%d", volume_num)
584 };
585 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
586 TEST_AND_RETURN_FALSE(exit_code == 0);
587
588 cmd = {
589 "ubiblock",
590 "--create",
591 volume_path
592 };
593 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
594 TEST_AND_RETURN_FALSE(exit_code == 0);
595
596 while (timeout > 0 && !FileExists(volume_path.c_str())) {
597 sleep(1);
598 timeout--;
599 }
600
601 return FileExists(volume_path.c_str());
602}
603
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800604// If |path| is absolute, or explicit relative to the current working directory,
605// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
606// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
607// resulting path.
608static const string PrependTmpdir(const string& path) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700609 if (path[0] == '/' || base::StartsWithASCII(path, "./", true) ||
610 base::StartsWithASCII(path, "../", true))
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800611 return path;
612
613 const char *tmpdir = getenv("TMPDIR");
614 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
615 return prefix + "/" + path;
616}
617
Alex Deymof329b932014-10-30 01:37:48 -0700618bool MakeTempFile(const string& base_filename_template,
619 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700620 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800621 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700622 DCHECK(filename || fd);
623 vector<char> buf(filename_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800624 memcpy(buf.data(), filename_template.data(), filename_template.size());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700625 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700626
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800627 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700628 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
629 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800630 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700631 }
632 if (fd) {
633 *fd = mkstemp_fd;
634 } else {
635 close(mkstemp_fd);
636 }
637 return true;
638}
639
Alex Deymof329b932014-10-30 01:37:48 -0700640bool MakeTempDirectory(const string& base_dirname_template,
641 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800642 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700643 DCHECK(dirname);
644 vector<char> buf(dirname_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800645 memcpy(buf.data(), dirname_template.data(), dirname_template.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700646 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700647
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800648 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700649 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800650 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700651 return true;
652}
653
adlr@google.com3defe6a2009-12-04 20:57:17 +0000654bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700655 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700656 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800657 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
658 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
659 for (const char* fstype : fstypes) {
660 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
661 nullptr);
662 if (rc == 0)
663 return true;
664
665 PLOG(WARNING) << "Unable to mount destination device " << device
666 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000667 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800668 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
669 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000670}
671
672bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700673 for (int num_retries = 0; ; ++num_retries) {
674 if (umount(mountpoint.c_str()) == 0)
675 break;
676
677 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
678 num_retries < kUnmountMaxNumOfRetries);
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800679 g_usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700680 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000681 return true;
682}
683
Alex Deymof329b932014-10-30 01:37:48 -0700684bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700685 int* out_block_count,
686 int* out_block_size) {
687 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700688 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700689 ScopedFdCloser fd_closer(&fd);
690 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
691}
692
693bool GetFilesystemSizeFromFD(int fd,
694 int* out_block_count,
695 int* out_block_size) {
696 TEST_AND_RETURN_FALSE(fd >= 0);
697
Alex Deymo192393b2014-11-10 15:58:38 -0800698 // Determine the filesystem size by directly reading the block count and
699 // block size information from the superblock. Supported FS are ext3 and
700 // squashfs.
701
702 // Read from the fd only once and detect in memory. The first 2 KiB is enough
703 // to read the ext2 superblock (located at offset 1024) and the squashfs
704 // superblock (located at offset 0).
705 const ssize_t kBufferSize = 2048;
706
707 uint8_t buffer[kBufferSize];
708 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
709 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700710 return false;
711 }
Alex Deymo192393b2014-11-10 15:58:38 -0800712
713 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
714 return true;
715 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
716 return true;
717
718 LOG(ERROR) << "Unable to determine file system type.";
719 return false;
720}
721
722bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
723 int* out_block_count,
724 int* out_block_size) {
725 // See include/linux/ext2_fs.h for more details on the structure. We obtain
726 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
727 // library.
728 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
729 return false;
730
731 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
732
733 // ext3_fs.h: ext3_super_block.s_blocks_count
734 uint32_t block_count =
735 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
736
737 // ext3_fs.h: ext3_super_block.s_log_block_size
738 uint32_t log_block_size =
739 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
740
741 // ext3_fs.h: ext3_super_block.s_magic
742 uint16_t magic =
743 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
744
Darin Petkovd3f8c892010-10-12 21:38:45 -0700745 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800746 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700747 magic = le16toh(magic);
748
749 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800750 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
751 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
752 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700753 TEST_AND_RETURN_FALSE(block_count > 0);
754
Alex Deymo192393b2014-11-10 15:58:38 -0800755 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700756 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800757 if (out_block_size)
758 *out_block_size = 1 << log_block_size;
759 return true;
760}
761
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800762bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800763 int* out_block_count,
764 int* out_block_size) {
765 // See fs/squashfs/squashfs_fs.h for format details. We only support
766 // Squashfs 4.x little endian.
767
768 // sizeof(struct squashfs_super_block)
769 const size_t kSquashfsSuperBlockSize = 96;
770 if (buffer_size < kSquashfsSuperBlockSize)
771 return false;
772
773 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
774 if (memcmp(buffer, "hsqs", 4) != 0)
775 return false; // Only little endian is supported.
776
777 // squashfs_fs.h: struct squashfs_super_block.s_major
778 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
779 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
780
781 if (s_major != 4) {
782 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
783 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700784 }
Alex Deymo192393b2014-11-10 15:58:38 -0800785
786 // squashfs_fs.h: struct squashfs_super_block.bytes_used
787 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
788 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
789
790 const int block_size = 4096;
791
792 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
793 // so we round up to the nearest blocksize.
794 if (out_block_count)
795 *out_block_count = (bytes_used + block_size - 1) / block_size;
796 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700797 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700798 return true;
799}
800
Alex Deymo60ca1a72015-06-18 18:19:15 -0700801bool IsExtFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700802 chromeos::Blob header;
803 // The first 2 KiB is enough to read the ext2 superblock (located at offset
804 // 1024).
805 if (!ReadFileChunk(device, 0, 2048, &header))
806 return false;
807 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
808}
809
Alex Deymo60ca1a72015-06-18 18:19:15 -0700810bool IsSquashfsFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700811 chromeos::Blob header;
812 // The first 96 is enough to read the squashfs superblock.
813 const ssize_t kSquashfsSuperBlockSize = 96;
814 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
815 return false;
816 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
817}
818
Alex Deymo032e7722014-03-25 17:53:56 -0700819// Tries to parse the header of an ELF file to obtain a human-readable
820// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800821static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
822 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700823 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700824 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700825 return false;
826 *output = "ELF";
827
828 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700829 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700830 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700831 switch (buffer[EI_CLASS]) {
832 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700833 *output += " 32-bit";
834 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700835 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700836 *output += " 64-bit";
837 break;
838 default:
839 *output += " ?-bit";
840 }
841
842 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700843 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700844 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800845 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700846 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700847 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700848 *output += " little-endian";
849 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700850 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700851 *output += " big-endian";
852 break;
853 default:
854 *output += " ?-endian";
855 // Don't parse anything after the 0x10 offset if endianness is unknown.
856 return true;
857 }
858
Alex Deymoc1711e22014-08-08 13:16:23 -0700859 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
860 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
861 // and size is the same for both 32 and 64 bits.
862 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700863 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700864 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700865 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700866 if (ei_data == ELFDATA2LSB)
867 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700868 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700869 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700870
871 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700872 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700873 *output += " x86";
874 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700875 case EM_MIPS:
876 *output += " mips";
877 break;
878 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700879 *output += " arm";
880 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700881 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700882 *output += " x86-64";
883 break;
884 default:
885 *output += " unknown-arch";
886 }
887 return true;
888}
889
890string GetFileFormat(const string& path) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800891 chromeos::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700892 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
893 return "File not found.";
894
895 string result;
896 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
897 return result;
898
899 return "data";
900}
901
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800902namespace {
903// Do the actual trigger. We do it as a main-loop callback to (try to) get a
904// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700905void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800906 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700907 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800908 if (pid == 0) {
909 // We are the child. Crash.
910 abort(); // never returns
911 }
912 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700913 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800914 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800915}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700916} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800917
918void ScheduleCrashReporterUpload() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700919 chromeos::MessageLoop::current()->PostTask(
920 FROM_HERE,
921 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800922}
923
Chris Sosa4f8ee272012-11-30 13:01:54 -0800924bool SetCpuShares(CpuShares shares) {
925 string string_shares = base::IntToString(static_cast<int>(shares));
926 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
927 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700928 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
929 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800930 return true;
931 } else {
932 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
933 << " using " << cpu_shares_file;
934 return false;
935 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700936}
937
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700938int FuzzInt(int value, unsigned int range) {
939 int min = value - range / 2;
940 int max = value + range - range / 2;
941 return base::RandInt(min, max);
942}
943
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700944string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800945 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700946}
947
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800948string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400949 string str;
950
951 // Handle negative durations by prefixing with a minus.
952 if (delta.ToInternalValue() < 0) {
953 delta *= -1;
954 str = "-";
955 }
956
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700957 // Canonicalize into days, hours, minutes, seconds and microseconds.
958 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800959 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700960 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800961 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700962 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800963 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700964 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800965 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700966 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800967
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700968 if (days)
969 base::StringAppendF(&str, "%ud", days);
970 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800971 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700972 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800973 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700974 base::StringAppendF(&str, "%u", secs);
975 if (usecs) {
976 int width = 6;
977 while ((usecs / 10) * 10 == usecs) {
978 usecs /= 10;
979 width--;
980 }
981 base::StringAppendF(&str, ".%0*u", width, usecs);
982 }
983 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800984 return str;
985}
986
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700987string ToString(const Time utc_time) {
988 Time::Exploded exp_time;
989 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700990 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700991 exp_time.month,
992 exp_time.day_of_month,
993 exp_time.year,
994 exp_time.hour,
995 exp_time.minute,
996 exp_time.second);
997}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000998
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700999string ToString(bool b) {
1000 return (b ? "true" : "false");
1001}
1002
Alex Deymo1c656c42013-06-28 11:02:14 -07001003string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001004 switch (source) {
1005 case kDownloadSourceHttpsServer: return "HttpsServer";
1006 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -07001007 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -07001008 case kNumDownloadSources: return "Unknown";
1009 // Don't add a default case to let the compiler warn about newly added
1010 // download sources which should be added here.
1011 }
1012
1013 return "Unknown";
1014}
1015
Alex Deymo1c656c42013-06-28 11:02:14 -07001016string ToString(PayloadType payload_type) {
1017 switch (payload_type) {
1018 case kPayloadTypeDelta: return "Delta";
1019 case kPayloadTypeFull: return "Full";
1020 case kPayloadTypeForcedFull: return "ForcedFull";
1021 case kNumPayloadTypes: return "Unknown";
1022 // Don't add a default case to let the compiler warn about newly added
1023 // payload types which should be added here.
1024 }
1025
1026 return "Unknown";
1027}
1028
David Zeuthena99981f2013-04-29 13:42:47 -07001029ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001030 // Ignore the higher order bits in the code by applying the mask as
1031 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001032 // with values less than ErrorCode::kUmaReportedMax.
1033 ErrorCode base_code = static_cast<ErrorCode>(
1034 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -07001035
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001036 // Make additional adjustments required for UMA and error classification.
1037 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
1038 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001039 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001040 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001041 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001042 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001043 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1044 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001045 }
1046
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001047 return base_code;
1048}
1049
David Zeuthen33bae492014-02-25 16:16:18 -08001050metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001051 ErrorCode base_code = static_cast<ErrorCode>(
1052 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001053
1054 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001055 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001056 return metrics::AttemptResult::kUpdateSucceeded;
1057
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001058 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001059 return metrics::AttemptResult::kPayloadDownloadError;
1060
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001061 case ErrorCode::kDownloadInvalidMetadataSize:
1062 case ErrorCode::kDownloadInvalidMetadataMagicString:
1063 case ErrorCode::kDownloadMetadataSignatureError:
1064 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1065 case ErrorCode::kPayloadMismatchedType:
1066 case ErrorCode::kUnsupportedMajorPayloadVersion:
1067 case ErrorCode::kUnsupportedMinorPayloadVersion:
1068 case ErrorCode::kDownloadNewPartitionInfoError:
1069 case ErrorCode::kDownloadSignatureMissingInManifest:
1070 case ErrorCode::kDownloadManifestParseError:
1071 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001072 return metrics::AttemptResult::kMetadataMalformed;
1073
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001074 case ErrorCode::kDownloadOperationHashMismatch:
1075 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001076 return metrics::AttemptResult::kOperationMalformed;
1077
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001078 case ErrorCode::kDownloadOperationExecutionError:
1079 case ErrorCode::kInstallDeviceOpenError:
1080 case ErrorCode::kKernelDeviceOpenError:
1081 case ErrorCode::kDownloadWriteError:
1082 case ErrorCode::kFilesystemCopierError:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001083 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001084 return metrics::AttemptResult::kOperationExecutionError;
1085
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001086 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001087 return metrics::AttemptResult::kMetadataVerificationFailed;
1088
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001089 case ErrorCode::kPayloadSizeMismatchError:
1090 case ErrorCode::kPayloadHashMismatchError:
1091 case ErrorCode::kDownloadPayloadVerificationError:
1092 case ErrorCode::kSignedDeltaPayloadExpectedError:
1093 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001094 return metrics::AttemptResult::kPayloadVerificationFailed;
1095
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001096 case ErrorCode::kNewRootfsVerificationError:
1097 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001098 return metrics::AttemptResult::kVerificationFailed;
1099
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001100 case ErrorCode::kPostinstallRunnerError:
1101 case ErrorCode::kPostinstallBootedFromFirmwareB:
1102 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001103 return metrics::AttemptResult::kPostInstallFailed;
1104
1105 // We should never get these errors in the update-attempt stage so
1106 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001107 case ErrorCode::kError:
1108 case ErrorCode::kOmahaRequestXMLParseError:
1109 case ErrorCode::kOmahaRequestError:
1110 case ErrorCode::kOmahaResponseHandlerError:
1111 case ErrorCode::kDownloadStateInitializationError:
1112 case ErrorCode::kOmahaRequestEmptyResponseError:
1113 case ErrorCode::kDownloadInvalidMetadataSignature:
1114 case ErrorCode::kOmahaResponseInvalid:
1115 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1116 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1117 case ErrorCode::kOmahaErrorInHTTPResponse:
1118 case ErrorCode::kDownloadMetadataSignatureMissingError:
1119 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1120 case ErrorCode::kPostinstallPowerwashError:
1121 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001122 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001123 return metrics::AttemptResult::kInternalError;
1124
1125 // Special flags. These can't happen (we mask them out above) but
1126 // the compiler doesn't know that. Just break out so we can warn and
1127 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001128 case ErrorCode::kUmaReportedMax:
1129 case ErrorCode::kOmahaRequestHTTPResponseBase:
1130 case ErrorCode::kDevModeFlag:
1131 case ErrorCode::kResumedFlag:
1132 case ErrorCode::kTestImageFlag:
1133 case ErrorCode::kTestOmahaUrlFlag:
1134 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001135 break;
1136 }
1137
1138 LOG(ERROR) << "Unexpected error code " << base_code;
1139 return metrics::AttemptResult::kInternalError;
1140}
1141
1142
1143metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001144 ErrorCode base_code = static_cast<ErrorCode>(
1145 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001146
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001147 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1148 int http_status =
1149 static_cast<int>(base_code) -
1150 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001151 if (http_status >= 200 && http_status <= 599) {
1152 return static_cast<metrics::DownloadErrorCode>(
1153 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1154 http_status - 200);
1155 } else if (http_status == 0) {
1156 // The code is using HTTP Status 0 for "Unable to get http
1157 // response code."
1158 return metrics::DownloadErrorCode::kDownloadError;
1159 }
1160 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1161 return metrics::DownloadErrorCode::kHttpStatusOther;
1162 }
1163
1164 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001165 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001166 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1167 //
1168 // For now just map that to kDownloading. See http://crbug.com/355745
1169 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001170 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001171 return metrics::DownloadErrorCode::kDownloadError;
1172
1173 // All of these error codes are not related to downloading so break
1174 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001175 case ErrorCode::kSuccess:
1176 case ErrorCode::kError:
1177 case ErrorCode::kOmahaRequestError:
1178 case ErrorCode::kOmahaResponseHandlerError:
1179 case ErrorCode::kFilesystemCopierError:
1180 case ErrorCode::kPostinstallRunnerError:
1181 case ErrorCode::kPayloadMismatchedType:
1182 case ErrorCode::kInstallDeviceOpenError:
1183 case ErrorCode::kKernelDeviceOpenError:
1184 case ErrorCode::kPayloadHashMismatchError:
1185 case ErrorCode::kPayloadSizeMismatchError:
1186 case ErrorCode::kDownloadPayloadVerificationError:
1187 case ErrorCode::kDownloadNewPartitionInfoError:
1188 case ErrorCode::kDownloadWriteError:
1189 case ErrorCode::kNewRootfsVerificationError:
1190 case ErrorCode::kNewKernelVerificationError:
1191 case ErrorCode::kSignedDeltaPayloadExpectedError:
1192 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1193 case ErrorCode::kPostinstallBootedFromFirmwareB:
1194 case ErrorCode::kDownloadStateInitializationError:
1195 case ErrorCode::kDownloadInvalidMetadataMagicString:
1196 case ErrorCode::kDownloadSignatureMissingInManifest:
1197 case ErrorCode::kDownloadManifestParseError:
1198 case ErrorCode::kDownloadMetadataSignatureError:
1199 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1200 case ErrorCode::kDownloadMetadataSignatureMismatch:
1201 case ErrorCode::kDownloadOperationHashVerificationError:
1202 case ErrorCode::kDownloadOperationExecutionError:
1203 case ErrorCode::kDownloadOperationHashMismatch:
1204 case ErrorCode::kOmahaRequestEmptyResponseError:
1205 case ErrorCode::kOmahaRequestXMLParseError:
1206 case ErrorCode::kDownloadInvalidMetadataSize:
1207 case ErrorCode::kDownloadInvalidMetadataSignature:
1208 case ErrorCode::kOmahaResponseInvalid:
1209 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1210 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1211 case ErrorCode::kOmahaErrorInHTTPResponse:
1212 case ErrorCode::kDownloadOperationHashMissingError:
1213 case ErrorCode::kDownloadMetadataSignatureMissingError:
1214 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1215 case ErrorCode::kPostinstallPowerwashError:
1216 case ErrorCode::kUpdateCanceledByChannelChange:
1217 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1218 case ErrorCode::kUnsupportedMajorPayloadVersion:
1219 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001220 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001221 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001222 break;
1223
1224 // Special flags. These can't happen (we mask them out above) but
1225 // the compiler doesn't know that. Just break out so we can warn and
1226 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001227 case ErrorCode::kUmaReportedMax:
1228 case ErrorCode::kOmahaRequestHTTPResponseBase:
1229 case ErrorCode::kDevModeFlag:
1230 case ErrorCode::kResumedFlag:
1231 case ErrorCode::kTestImageFlag:
1232 case ErrorCode::kTestOmahaUrlFlag:
1233 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001234 LOG(ERROR) << "Unexpected error code " << base_code;
1235 break;
1236 }
1237
1238 return metrics::DownloadErrorCode::kInputMalformed;
1239}
1240
David Zeuthenb281f072014-04-02 10:20:19 -07001241metrics::ConnectionType GetConnectionType(
1242 NetworkConnectionType type,
1243 NetworkTethering tethering) {
1244 switch (type) {
1245 case kNetUnknown:
1246 return metrics::ConnectionType::kUnknown;
1247
1248 case kNetEthernet:
1249 if (tethering == NetworkTethering::kConfirmed)
1250 return metrics::ConnectionType::kTetheredEthernet;
1251 else
1252 return metrics::ConnectionType::kEthernet;
1253
1254 case kNetWifi:
1255 if (tethering == NetworkTethering::kConfirmed)
1256 return metrics::ConnectionType::kTetheredWifi;
1257 else
1258 return metrics::ConnectionType::kWifi;
1259
1260 case kNetWimax:
1261 return metrics::ConnectionType::kWimax;
1262
1263 case kNetBluetooth:
1264 return metrics::ConnectionType::kBluetooth;
1265
1266 case kNetCellular:
1267 return metrics::ConnectionType::kCellular;
1268 }
1269
1270 LOG(ERROR) << "Unexpected network connection type: type=" << type
1271 << ", tethering=" << static_cast<int>(tethering);
1272
1273 return metrics::ConnectionType::kUnknown;
1274}
1275
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001276// Returns a printable version of the various flags denoted in the higher order
1277// bits of the given code. Returns an empty string if none of those bits are
1278// set.
1279string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001280 uint32_t flags = (static_cast<uint32_t>(code) &
1281 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001282 string flag_names;
1283 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001284 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001285 uint32_t flag = flags & (1 << i);
1286 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001287 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001288 separator = ", ";
1289 }
1290 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001291
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001292 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001293}
1294
David Zeuthena99981f2013-04-29 13:42:47 -07001295void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001296 if (!system_state)
1297 return;
1298
David Zeuthena99981f2013-04-29 13:42:47 -07001299 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001300
1301 // If the code doesn't have flags computed already, compute them now based on
1302 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001303 uint32_t flags =
1304 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001305 if (!flags)
1306 flags = system_state->update_attempter()->GetErrorCodeFlags();
1307
1308 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1309 // flag, as it's perfectly normal for production devices to resume their
1310 // downloads and so we want to record those cases also in NormalErrorCodes
1311 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001312 string metric =
1313 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001314 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1315
1316 LOG(INFO) << "Sending error code " << uma_error_code
1317 << " (" << CodeToString(uma_error_code) << ")"
1318 << " to UMA metric: " << metric
1319 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1320
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001321 system_state->metrics_lib()->SendEnumToUMA(
1322 metric, static_cast<int>(uma_error_code),
1323 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001324}
1325
David Zeuthena99981f2013-04-29 13:42:47 -07001326string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001327 // If the given code has both parts (i.e. the error code part and the flags
1328 // part) then strip off the flags part since the switch statement below
1329 // has case statements only for the base error code or a single flag but
1330 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001331 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1332 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1333 code = static_cast<ErrorCode>(
1334 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001335 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001336 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1337 case ErrorCode::kError: return "ErrorCode::kError";
1338 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1339 case ErrorCode::kOmahaResponseHandlerError:
1340 return "ErrorCode::kOmahaResponseHandlerError";
1341 case ErrorCode::kFilesystemCopierError:
1342 return "ErrorCode::kFilesystemCopierError";
1343 case ErrorCode::kPostinstallRunnerError:
1344 return "ErrorCode::kPostinstallRunnerError";
1345 case ErrorCode::kPayloadMismatchedType:
1346 return "ErrorCode::kPayloadMismatchedType";
1347 case ErrorCode::kInstallDeviceOpenError:
1348 return "ErrorCode::kInstallDeviceOpenError";
1349 case ErrorCode::kKernelDeviceOpenError:
1350 return "ErrorCode::kKernelDeviceOpenError";
1351 case ErrorCode::kDownloadTransferError:
1352 return "ErrorCode::kDownloadTransferError";
1353 case ErrorCode::kPayloadHashMismatchError:
1354 return "ErrorCode::kPayloadHashMismatchError";
1355 case ErrorCode::kPayloadSizeMismatchError:
1356 return "ErrorCode::kPayloadSizeMismatchError";
1357 case ErrorCode::kDownloadPayloadVerificationError:
1358 return "ErrorCode::kDownloadPayloadVerificationError";
1359 case ErrorCode::kDownloadNewPartitionInfoError:
1360 return "ErrorCode::kDownloadNewPartitionInfoError";
1361 case ErrorCode::kDownloadWriteError:
1362 return "ErrorCode::kDownloadWriteError";
1363 case ErrorCode::kNewRootfsVerificationError:
1364 return "ErrorCode::kNewRootfsVerificationError";
1365 case ErrorCode::kNewKernelVerificationError:
1366 return "ErrorCode::kNewKernelVerificationError";
1367 case ErrorCode::kSignedDeltaPayloadExpectedError:
1368 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1369 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1370 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1371 case ErrorCode::kPostinstallBootedFromFirmwareB:
1372 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1373 case ErrorCode::kDownloadStateInitializationError:
1374 return "ErrorCode::kDownloadStateInitializationError";
1375 case ErrorCode::kDownloadInvalidMetadataMagicString:
1376 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1377 case ErrorCode::kDownloadSignatureMissingInManifest:
1378 return "ErrorCode::kDownloadSignatureMissingInManifest";
1379 case ErrorCode::kDownloadManifestParseError:
1380 return "ErrorCode::kDownloadManifestParseError";
1381 case ErrorCode::kDownloadMetadataSignatureError:
1382 return "ErrorCode::kDownloadMetadataSignatureError";
1383 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1384 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1385 case ErrorCode::kDownloadMetadataSignatureMismatch:
1386 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1387 case ErrorCode::kDownloadOperationHashVerificationError:
1388 return "ErrorCode::kDownloadOperationHashVerificationError";
1389 case ErrorCode::kDownloadOperationExecutionError:
1390 return "ErrorCode::kDownloadOperationExecutionError";
1391 case ErrorCode::kDownloadOperationHashMismatch:
1392 return "ErrorCode::kDownloadOperationHashMismatch";
1393 case ErrorCode::kOmahaRequestEmptyResponseError:
1394 return "ErrorCode::kOmahaRequestEmptyResponseError";
1395 case ErrorCode::kOmahaRequestXMLParseError:
1396 return "ErrorCode::kOmahaRequestXMLParseError";
1397 case ErrorCode::kDownloadInvalidMetadataSize:
1398 return "ErrorCode::kDownloadInvalidMetadataSize";
1399 case ErrorCode::kDownloadInvalidMetadataSignature:
1400 return "ErrorCode::kDownloadInvalidMetadataSignature";
1401 case ErrorCode::kOmahaResponseInvalid:
1402 return "ErrorCode::kOmahaResponseInvalid";
1403 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1404 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1405 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1406 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1407 case ErrorCode::kOmahaErrorInHTTPResponse:
1408 return "ErrorCode::kOmahaErrorInHTTPResponse";
1409 case ErrorCode::kDownloadOperationHashMissingError:
1410 return "ErrorCode::kDownloadOperationHashMissingError";
1411 case ErrorCode::kDownloadMetadataSignatureMissingError:
1412 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1413 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1414 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1415 case ErrorCode::kPostinstallPowerwashError:
1416 return "ErrorCode::kPostinstallPowerwashError";
1417 case ErrorCode::kUpdateCanceledByChannelChange:
1418 return "ErrorCode::kUpdateCanceledByChannelChange";
1419 case ErrorCode::kUmaReportedMax:
1420 return "ErrorCode::kUmaReportedMax";
1421 case ErrorCode::kOmahaRequestHTTPResponseBase:
1422 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1423 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001424 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001425 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001426 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001427 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001428 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001429 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001430 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001431 case ErrorCode::kSpecialFlags:
1432 return "ErrorCode::kSpecialFlags";
1433 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1434 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1435 case ErrorCode::kUnsupportedMajorPayloadVersion:
1436 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1437 case ErrorCode::kUnsupportedMinorPayloadVersion:
1438 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001439 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1440 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Allie Woodeb9e6d82015-04-17 13:55:30 -07001441 case ErrorCode::kFilesystemVerifierError:
1442 return "ErrorCode::kFilesystemVerifierError";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001443 // Don't add a default case to let the compiler warn about newly added
1444 // error codes which should be added here.
1445 }
1446
1447 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1448}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001449
Gilad Arnold30dedd82013-07-03 06:19:09 -07001450bool CreatePowerwashMarkerFile(const char* file_path) {
1451 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1452 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001453 kPowerwashCommand,
1454 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001455 if (result) {
1456 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1457 } else {
1458 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1459 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001460
1461 return result;
1462}
1463
Gilad Arnold30dedd82013-07-03 06:19:09 -07001464bool DeletePowerwashMarkerFile(const char* file_path) {
1465 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001466 const base::FilePath kPowerwashMarkerPath(marker_file);
1467 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001468
1469 if (result)
1470 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001471 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001472 else
1473 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001474 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001475
1476 return result;
1477}
1478
Alex Deymof329b932014-10-30 01:37:48 -07001479bool GetInstallDev(const string& boot_dev, string* install_dev) {
1480 string disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001481 int partition_num;
1482 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1483 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001484
Chris Sosad317e402013-06-12 13:47:09 -07001485 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001486 if (partition_num == 3) {
1487 partition_num = 5;
1488 } else if (partition_num == 5) {
1489 partition_num = 3;
1490 } else {
1491 return false;
1492 }
1493
1494 if (install_dev)
1495 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001496
Chris Sosad317e402013-06-12 13:47:09 -07001497 return true;
1498}
1499
David Zeuthen27a48bc2013-08-06 12:06:29 -07001500Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001501 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1502 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001503 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1504}
1505
Alex Deymof329b932014-10-30 01:37:48 -07001506gchar** StringVectorToGStrv(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001507 GPtrArray *p = g_ptr_array_new();
Alex Deymo020600d2014-11-05 21:05:55 -08001508 for (const string& str : vec_str) {
1509 g_ptr_array_add(p, g_strdup(str.c_str()));
David Zeuthen27a48bc2013-08-06 12:06:29 -07001510 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001511 g_ptr_array_add(p, nullptr);
David Zeuthen27a48bc2013-08-06 12:06:29 -07001512 return reinterpret_cast<gchar**>(g_ptr_array_free(p, FALSE));
1513}
1514
Alex Deymof329b932014-10-30 01:37:48 -07001515string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001516 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001517 for (vector<string>::const_iterator i = vec_str.begin();
1518 i != vec_str.end(); ++i) {
1519 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001520 str += ", ";
1521 str += '"';
1522 str += *i;
1523 str += '"';
1524 }
1525 str += "]";
1526 return str;
1527}
1528
David Zeuthen8f191b22013-08-06 12:27:50 -07001529string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001530 string encoded_hash = chromeos::data_encoding::Base64Encode(payload_hash);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001531 return base::StringPrintf("cros_update_size_%zu_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001532 payload_size,
1533 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001534}
1535
Alex Deymof329b932014-10-30 01:37:48 -07001536bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001537 base::FilePath *out_path) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001538 chromeos::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001539
1540 out_path->clear();
1541
1542 if (base64_encoded.size() == 0) {
1543 LOG(ERROR) << "Can't decode empty string.";
1544 return false;
1545 }
1546
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001547 if (!chromeos::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001548 contents.size() == 0) {
1549 LOG(ERROR) << "Error decoding base64.";
1550 return false;
1551 }
1552
Alex Vakulenko75039d72014-03-25 12:36:28 -07001553 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001554 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001555 LOG(ERROR) << "Error creating temporary file.";
1556 return false;
1557 }
1558
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001559 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001560 PLOG(ERROR) << "Error writing to temporary file.";
1561 if (fclose(file) != 0)
1562 PLOG(ERROR) << "Error closing temporary file.";
1563 if (unlink(out_path->value().c_str()) != 0)
1564 PLOG(ERROR) << "Error unlinking temporary file.";
1565 out_path->clear();
1566 return false;
1567 }
1568
1569 if (fclose(file) != 0) {
1570 PLOG(ERROR) << "Error closing temporary file.";
1571 out_path->clear();
1572 return false;
1573 }
1574
1575 return true;
1576}
1577
Alex Deymof329b932014-10-30 01:37:48 -07001578bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001579 time_t unix_time = time.ToTimeT();
1580 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1581 const time_t kOmahaEpoch = 1167638400;
1582 const int64_t kNumSecondsPerWeek = 7*24*3600;
1583 const int64_t kNumDaysPerWeek = 7;
1584
1585 time_t omaha_time = unix_time - kOmahaEpoch;
1586
1587 if (omaha_time < 0)
1588 return false;
1589
1590 // Note, as per the comment in utils.h we are deliberately not
1591 // handling DST correctly.
1592
1593 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1594 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1595
1596 return true;
1597}
1598
David Zeuthen33bae492014-02-25 16:16:18 -08001599bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001600 const string& state_variable_key,
1601 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001602 bool ret = false;
1603
Alex Deymof329b932014-10-30 01:37:48 -07001604 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001605 int64_t stored_value;
1606 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001607 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001608 if (stored_time > now) {
1609 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1610 << " is in the future.";
1611 } else {
1612 *out_duration = now - stored_time;
1613 ret = true;
1614 }
1615 }
1616
1617 if (!system_state->prefs()->SetInt64(state_variable_key,
1618 now.ToInternalValue())) {
1619 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1620 }
1621
1622 return ret;
1623}
1624
1625bool MonotonicDurationHelper(SystemState* system_state,
1626 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001627 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001628 bool ret = false;
1629
Alex Deymof329b932014-10-30 01:37:48 -07001630 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001631 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001632 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001633 *out_duration = now - stored_time;
1634 ret = true;
1635 }
1636 *storage = now.ToInternalValue();
1637
1638 return ret;
1639}
1640
Allie Wood78750a42015-02-11 15:42:11 -08001641bool GetMinorVersion(base::FilePath path, uint32_t* minor_version) {
1642 chromeos::KeyValueStore store;
Alex Deymo60ca1a72015-06-18 18:19:15 -07001643 string result;
Allie Wood78750a42015-02-11 15:42:11 -08001644 if (base::PathExists(path) && store.Load(path) &&
1645 store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001646 if (!base::StringToUint(result, minor_version)) {
1647 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1648 return false;
1649 }
Allie Wood78750a42015-02-11 15:42:11 -08001650 return true;
1651 }
1652 return false;
1653}
1654
Alex Deymo60ca1a72015-06-18 18:19:15 -07001655bool ReadExtents(const string& path, const vector<Extent>& extents,
Allie Wood56873452015-03-27 17:48:40 -07001656 chromeos::Blob* out_data, ssize_t out_data_size,
1657 size_t block_size) {
1658 chromeos::Blob data(out_data_size);
1659 ssize_t bytes_read = 0;
1660 int fd = open(path.c_str(), O_RDONLY);
1661 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1662 ScopedFdCloser fd_closer(&fd);
1663
Gilad Arnold41e34742015-05-11 11:31:50 -07001664 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001665 ssize_t bytes_read_this_iteration = 0;
1666 ssize_t bytes = extent.num_blocks() * block_size;
1667 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1668 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1669 &data[bytes_read],
1670 bytes,
1671 extent.start_block() * block_size,
1672 &bytes_read_this_iteration));
1673 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1674 bytes_read += bytes_read_this_iteration;
1675 }
1676 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1677 *out_data = data;
1678 return true;
1679}
1680
adlr@google.com3defe6a2009-12-04 20:57:17 +00001681} // namespace utils
1682
1683} // namespace chromeos_update_engine