blob: ebc849ed33bfb991bc682da1f5defcf9b969e37d [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
adlr@google.com3defe6a2009-12-04 20:57:17 +000016
17#include "update_engine/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -070018
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <dirent.h>
Alex Deymoc1711e22014-08-08 13:16:23 -070022#include <elf.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000023#include <errno.h>
Alex Deymo192393b2014-11-10 15:58:38 -080024#include <ext2fs/ext2fs.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080025#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000026#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070029#include <sys/mount.h>
30#include <sys/resource.h>
31#include <sys/stat.h>
32#include <sys/types.h>
33#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000034#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070035
adlr@google.com3defe6a2009-12-04 20:57:17 +000036#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070037#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070038#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070039
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070040#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070041#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080042#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070043#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070044#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070045#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040046#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080047#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050048#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070049#include <base/strings/string_number_conversions.h>
50#include <base/strings/string_split.h>
51#include <base/strings/string_util.h>
52#include <base/strings/stringprintf.h>
Alex Vakulenko981a9fb2015-02-09 12:51:24 -080053#include <chromeos/data_encoding.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070054#include <chromeos/message_loops/message_loop.h>
Will Drewry8f71da82010-08-30 14:07:11 -050055
David Zeuthen33bae492014-02-25 16:16:18 -080056#include "update_engine/clock_interface.h"
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070057#include "update_engine/constants.h"
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080058#include "update_engine/file_descriptor.h"
Andrew de los Reyes970bb282009-12-09 16:34:04 -080059#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070060#include "update_engine/omaha_request_params.h"
David Zeuthen33bae492014-02-25 16:16:18 -080061#include "update_engine/prefs_interface.h"
Darin Petkov296889c2010-07-23 16:20:54 -070062#include "update_engine/subprocess.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080063#include "update_engine/system_state.h"
64#include "update_engine/update_attempter.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000065
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070066using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080067using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000068using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070069using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000070using std::string;
71using std::vector;
72
73namespace chromeos_update_engine {
74
Ben Chan77a1eba2012-10-07 22:54:55 -070075namespace {
76
77// The following constants control how UnmountFilesystem should retry if
78// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
79// one second.
80const int kUnmountMaxNumOfRetries = 5;
81const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070082
83// Number of bytes to read from a file to attempt to detect its contents. Used
84// in GetFileFormat.
85const int kGetFileFormatMaxHeaderSize = 32;
86
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080087// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
88// simply based on the name of the device.
89bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -070090 return base::StartsWithASCII(disk_name, "/dev/ubi", true) ||
91 base::StartsWithASCII(disk_name, "/dev/mtd", true);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080092}
93
94// Return the device name for the corresponding partition on a NAND device.
95// WARNING: This function returns device names that are not mountable.
96string MakeNandPartitionName(int partition_num) {
97 switch (partition_num) {
98 case 2:
99 case 4:
100 case 6: {
101 return base::StringPrintf("/dev/mtd%d", partition_num);
102 }
103 default: {
104 return base::StringPrintf("/dev/ubi%d_0", partition_num);
105 }
106 }
107}
108
109// Return the device name for the corresponding partition on a NAND device that
110// may be mountable (but may not be writable).
111string MakeNandPartitionNameForMount(int partition_num) {
112 switch (partition_num) {
113 case 2:
114 case 4:
115 case 6: {
116 return base::StringPrintf("/dev/mtd%d", partition_num);
117 }
118 case 3:
119 case 5:
120 case 7: {
121 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
122 }
123 default: {
124 return base::StringPrintf("/dev/ubi%d_0", partition_num);
125 }
126 }
127}
128
Ben Chan77a1eba2012-10-07 22:54:55 -0700129} // namespace
130
adlr@google.com3defe6a2009-12-04 20:57:17 +0000131namespace utils {
132
Chris Sosa4f8ee272012-11-30 13:01:54 -0800133// Cgroup container is created in update-engine's upstart script located at
134// /etc/init/update-engine.conf.
135static const char kCGroupDir[] = "/sys/fs/cgroup/cpu/update-engine";
136
J. Richard Barnette63137e52013-10-28 10:57:29 -0700137string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700138 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700139
Alex Vakulenko75039d72014-03-25 12:36:28 -0700140 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700141 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700142 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700143 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800144 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700145 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800146 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700147 string output;
148 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800149 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700150 return output;
151 }
152 }
153 }
154 LOG(ERROR) << "Unable to parse fwid from ec info.";
155 return "";
156}
157
158
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700159const string KernelDeviceOfBootDevice(const string& boot_device) {
160 string kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700161
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700162 string disk_name;
163 int partition_num;
164 if (SplitPartitionName(boot_device, &disk_name, &partition_num)) {
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700165 // Currently this assumes the partition number of the boot device is
166 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
167 // get the kernel device.
168 if (partition_num == 3 || partition_num == 5 || partition_num == 7) {
169 kernel_partition_name = MakePartitionName(disk_name, partition_num - 1);
170 }
J. Richard Barnette30842932013-10-28 15:04:23 -0700171 }
172
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700173 return kernel_partition_name;
J. Richard Barnette30842932013-10-28 15:04:23 -0700174}
175
176
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800177bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800178 DirectFileWriter writer;
179 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
180 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700181 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800182 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800183 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800184 return true;
185}
186
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700187bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700188 const char* c_buf = static_cast<const char*>(buf);
189 ssize_t bytes_written = 0;
190 while (bytes_written < static_cast<ssize_t>(count)) {
191 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
192 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
193 bytes_written += rc;
194 }
195 return true;
196}
197
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700198bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
199 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700200 size_t bytes_written = 0;
201 int num_attempts = 0;
202 while (bytes_written < count) {
203 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700204 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
205 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700206 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
207 if (rc < 0) {
208 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
209 << " bytes_written=" << bytes_written
210 << " count=" << count << " offset=" << offset;
211 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700212 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
213 bytes_written += rc;
214 }
215 return true;
216}
217
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800218bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
219 const char* c_buf = static_cast<const char*>(buf);
220 ssize_t bytes_written = 0;
221 while (bytes_written < static_cast<ssize_t>(count)) {
222 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
223 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
224 bytes_written += rc;
225 }
226 return true;
227}
228
229bool PWriteAll(FileDescriptorPtr fd,
230 const void* buf,
231 size_t count,
232 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700233 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
234 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800235 return WriteAll(fd, buf, count);
236}
237
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700238bool PReadAll(int fd, void* buf, size_t count, off_t offset,
239 ssize_t* out_bytes_read) {
240 char* c_buf = static_cast<char*>(buf);
241 ssize_t bytes_read = 0;
242 while (bytes_read < static_cast<ssize_t>(count)) {
243 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
244 offset + bytes_read);
245 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
246 if (rc == 0) {
247 break;
248 }
249 bytes_read += rc;
250 }
251 *out_bytes_read = bytes_read;
252 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700253}
254
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800255bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
256 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700257 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
258 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800259 char* c_buf = static_cast<char*>(buf);
260 ssize_t bytes_read = 0;
261 while (bytes_read < static_cast<ssize_t>(count)) {
262 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
263 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
264 if (rc == 0) {
265 break;
266 }
267 bytes_read += rc;
268 }
269 *out_bytes_read = bytes_read;
270 return true;
271}
272
Gilad Arnold19a45f02012-07-19 12:36:10 -0700273// Append |nbytes| of content from |buf| to the vector pointed to by either
274// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800275static void AppendBytes(const uint8_t* buf, size_t nbytes,
276 chromeos::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700277 CHECK(buf);
278 CHECK(vec_p);
279 vec_p->insert(vec_p->end(), buf, buf + nbytes);
280}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800281static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700282 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700283 CHECK(buf);
284 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800285 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700286}
287
288// Reads from an open file |fp|, appending the read content to the container
289// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200290// file's content, false otherwise. If |size| is not -1, reads up to |size|
291// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700292template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200293static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700294 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200295 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800296 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200297 while (size == -1 || size > 0) {
298 off_t bytes_to_read = sizeof(buf);
299 if (size > 0 && bytes_to_read > size) {
300 bytes_to_read = size;
301 }
302 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
303 if (!nbytes) {
304 break;
305 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700306 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200307 if (size != -1) {
308 CHECK(size >= static_cast<off_t>(nbytes));
309 size -= nbytes;
310 }
311 }
312 if (ferror(fp)) {
313 return false;
314 }
315 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700316}
317
Darin Petkov8e447e02013-04-16 16:23:50 +0200318// Opens a file |path| for reading and appends its the contents to a container
319// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
320// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700321template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700322static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200323 off_t offset,
324 off_t size,
325 T* out_p) {
326 CHECK_GE(offset, 0);
327 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700328 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200329 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000330 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200331 if (offset) {
332 // Return success without appending any data if a chunk beyond the end of
333 // the file is requested.
334 if (offset >= FileSize(path)) {
335 return true;
336 }
337 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
338 }
339 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000340}
341
Alex Deymo10875d92014-11-10 21:52:57 -0800342// TODO(deymo): This is only used in unittest, but requires the private
343// Read<string>() defined here. Expose Read<string>() or move to base/ version.
344bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700345 FILE* fp = popen(cmd.c_str(), "r");
346 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000347 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200348 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700349 return (success && pclose(fp) >= 0);
350}
351
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800352bool ReadFile(const string& path, chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200353 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700354}
355
Darin Petkov8e447e02013-04-16 16:23:50 +0200356bool ReadFile(const string& path, string* out_p) {
357 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700358}
359
Darin Petkov8e447e02013-04-16 16:23:50 +0200360bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800361 chromeos::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200362 return ReadFileChunkAndAppend(path, offset, size, out_p);
363}
364
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700365off_t BlockDevSize(int fd) {
366 uint64_t dev_size;
367 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
368 if (rc == -1) {
369 dev_size = -1;
370 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
371 }
372 return dev_size;
373}
374
375off_t BlockDevSize(const string& path) {
376 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
377 if (fd == -1) {
378 PLOG(ERROR) << "Error opening " << path;
379 return fd;
380 }
381
382 off_t dev_size = BlockDevSize(fd);
383 if (dev_size == -1)
384 PLOG(ERROR) << "Error getting block device size on " << path;
385
386 close(fd);
387 return dev_size;
388}
389
390off_t FileSize(int fd) {
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700391 struct stat stbuf;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700392 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700393 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700394 if (rc < 0) {
395 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700396 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700397 }
398 if (S_ISREG(stbuf.st_mode))
399 return stbuf.st_size;
400 if (S_ISBLK(stbuf.st_mode))
401 return BlockDevSize(fd);
402 LOG(ERROR) << "Couldn't determine the type of " << fd;
403 return -1;
404}
405
406off_t FileSize(const string& path) {
407 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
408 if (fd == -1) {
409 PLOG(ERROR) << "Error opening " << path;
410 return fd;
411 }
412 off_t size = FileSize(fd);
413 if (size == -1)
414 PLOG(ERROR) << "Error getting file size of " << path;
415 close(fd);
416 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700417}
418
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800419void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000420 LOG(INFO) << "Logging array of length: " << length;
421 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700422 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000423 const unsigned int bytes_remaining = length - i;
424 const unsigned int bytes_per_this_line = min(bytes_per_line,
425 bytes_remaining);
426 char header[100];
427 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
428 TEST_AND_RETURN(r == 13);
429 string line = header;
430 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
431 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800432 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000433 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
434 TEST_AND_RETURN(r == 3);
435 line += buf;
436 }
437 LOG(INFO) << line;
438 }
439}
440
Alex Deymof329b932014-10-30 01:37:48 -0700441string GetDiskName(const string& partition_name) {
442 string disk_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800443 return SplitPartitionName(partition_name, &disk_name, nullptr) ?
Alex Deymof329b932014-10-30 01:37:48 -0700444 disk_name : string();
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700445}
446
Alex Deymof329b932014-10-30 01:37:48 -0700447int GetPartitionNumber(const string& partition_name) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800448 int partition_num = 0;
449 return SplitPartitionName(partition_name, nullptr, &partition_num) ?
450 partition_num : 0;
451}
452
Alex Deymof329b932014-10-30 01:37:48 -0700453bool SplitPartitionName(const string& partition_name,
454 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800455 int* out_partition_num) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700456 if (!base::StartsWithASCII(partition_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800457 LOG(ERROR) << "Invalid partition device name: " << partition_name;
458 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700459 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800460
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700461 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
462 if (last_nondigit_pos == string::npos ||
463 (last_nondigit_pos + 1) == partition_name.size()) {
464 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800465 return false;
466 }
467
Alex Deymof329b932014-10-30 01:37:48 -0700468 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700469 if (partition_name[last_nondigit_pos] == '_') {
470 // NAND block devices have weird naming which could be something
471 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
472 size_t prev_nondigit_pos =
473 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
474 if (prev_nondigit_pos == string::npos ||
475 (prev_nondigit_pos + 1) == last_nondigit_pos) {
476 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
477 return false;
478 }
479
480 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
481 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800482 }
483
484 if (out_disk_name) {
485 // Special case for MMC devices which have the following naming scheme:
486 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700487 size_t disk_name_len = last_nondigit_pos;
488 if (partition_name[last_nondigit_pos] != 'p' ||
489 last_nondigit_pos == 0 ||
490 !isdigit(partition_name[last_nondigit_pos - 1])) {
491 disk_name_len++;
492 }
493 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800494 }
495
496 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700497 string partition_str = partition_name.substr(last_nondigit_pos + 1,
498 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800499 *out_partition_num = atoi(partition_str.c_str());
500 }
501 return true;
502}
503
Alex Deymof329b932014-10-30 01:37:48 -0700504string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800505 if (partition_num < 1) {
506 LOG(ERROR) << "Invalid partition number: " << partition_num;
507 return string();
508 }
509
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700510 if (!base::StartsWithASCII(disk_name, "/dev/", true)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800511 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700512 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800513 }
514
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800515 if (IsMtdDeviceName(disk_name)) {
516 // Special case for UBI block devices.
517 // 1. ubiblock is not writable, we need to use plain "ubi".
518 // 2. There is a "_0" suffix.
519 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800520 }
521
Alex Deymof329b932014-10-30 01:37:48 -0700522 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700523 if (isdigit(partition_name.back())) {
524 // Special case for devices with names ending with a digit.
525 // Add "p" to separate the disk name from partition number,
526 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800527 partition_name += 'p';
528 }
529
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700530 partition_name += std::to_string(partition_num);
531
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800532 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700533}
534
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800535string MakePartitionNameForMount(const string& part_name) {
536 if (IsMtdDeviceName(part_name)) {
537 int partition_num;
538 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
539 return "";
540 }
541 return MakeNandPartitionNameForMount(partition_num);
542 }
543 return part_name;
544}
545
Darin Petkovf74eb652010-08-04 12:08:38 -0700546string SysfsBlockDevice(const string& device) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700547 base::FilePath device_path(device);
Darin Petkovf74eb652010-08-04 12:08:38 -0700548 if (device_path.DirName().value() != "/dev") {
549 return "";
550 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700551 return base::FilePath("/sys/block").Append(device_path.BaseName()).value();
Darin Petkovf74eb652010-08-04 12:08:38 -0700552}
553
Alex Deymof329b932014-10-30 01:37:48 -0700554bool IsRemovableDevice(const string& device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700555 string sysfs_block = SysfsBlockDevice(device);
556 string removable;
557 if (sysfs_block.empty() ||
Alex Vakulenko75039d72014-03-25 12:36:28 -0700558 !base::ReadFileToString(base::FilePath(sysfs_block).Append("removable"),
Ben Chan736fcb52014-05-21 18:28:22 -0700559 &removable)) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700560 return false;
561 }
Ben Chan736fcb52014-05-21 18:28:22 -0700562 base::TrimWhitespaceASCII(removable, base::TRIM_ALL, &removable);
Darin Petkovf74eb652010-08-04 12:08:38 -0700563 return removable == "1";
564}
565
Alex Deymof329b932014-10-30 01:37:48 -0700566string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000567 char buf[100];
568 buf[0] = '\0';
569 return strerror_r(err, buf, sizeof(buf));
570}
571
adlr@google.com3defe6a2009-12-04 20:57:17 +0000572bool FileExists(const char* path) {
573 struct stat stbuf;
574 return 0 == lstat(path, &stbuf);
575}
576
Darin Petkov30291ed2010-11-12 10:23:06 -0800577bool IsSymlink(const char* path) {
578 struct stat stbuf;
579 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
580}
581
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800582bool TryAttachingUbiVolume(int volume_num, int timeout) {
583 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
584 if (FileExists(volume_path.c_str())) {
585 return true;
586 }
587
588 int exit_code;
589 vector<string> cmd = {
590 "ubiattach",
591 "-m",
592 base::StringPrintf("%d", volume_num),
593 "-d",
594 base::StringPrintf("%d", volume_num)
595 };
596 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
597 TEST_AND_RETURN_FALSE(exit_code == 0);
598
599 cmd = {
600 "ubiblock",
601 "--create",
602 volume_path
603 };
604 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
605 TEST_AND_RETURN_FALSE(exit_code == 0);
606
607 while (timeout > 0 && !FileExists(volume_path.c_str())) {
608 sleep(1);
609 timeout--;
610 }
611
612 return FileExists(volume_path.c_str());
613}
614
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800615// If |path| is absolute, or explicit relative to the current working directory,
616// leaves it as is. Otherwise, if TMPDIR is defined in the environment and is
617// non-empty, prepends it to |path|. Otherwise, prepends /tmp. Returns the
618// resulting path.
619static const string PrependTmpdir(const string& path) {
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700620 if (path[0] == '/' || base::StartsWithASCII(path, "./", true) ||
621 base::StartsWithASCII(path, "../", true))
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800622 return path;
623
624 const char *tmpdir = getenv("TMPDIR");
625 const string prefix = (tmpdir && *tmpdir ? tmpdir : "/tmp");
626 return prefix + "/" + path;
627}
628
Alex Deymof329b932014-10-30 01:37:48 -0700629bool MakeTempFile(const string& base_filename_template,
630 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700631 int* fd) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800632 const string filename_template = PrependTmpdir(base_filename_template);
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700633 DCHECK(filename || fd);
634 vector<char> buf(filename_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800635 memcpy(buf.data(), filename_template.data(), filename_template.size());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700636 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700637
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800638 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700639 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
640 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800641 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700642 }
643 if (fd) {
644 *fd = mkstemp_fd;
645 } else {
646 close(mkstemp_fd);
647 }
648 return true;
649}
650
Alex Deymof329b932014-10-30 01:37:48 -0700651bool MakeTempDirectory(const string& base_dirname_template,
652 string* dirname) {
Gilad Arnoldd04f8e22014-01-09 13:13:40 -0800653 const string dirname_template = PrependTmpdir(base_dirname_template);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700654 DCHECK(dirname);
655 vector<char> buf(dirname_template.size() + 1);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800656 memcpy(buf.data(), dirname_template.data(), dirname_template.size());
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700657 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700658
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800659 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700660 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800661 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700662 return true;
663}
664
adlr@google.com3defe6a2009-12-04 20:57:17 +0000665bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700666 const string& mountpoint,
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700667 unsigned long mountflags) { // NOLINT(runtime/int)
Alex Deymo4c82df32014-11-10 22:25:57 -0800668 // TODO(sosa): Remove "ext3" once crbug.com/208022 is resolved.
669 const vector<const char*> fstypes{"ext2", "ext3", "squashfs"};
670 for (const char* fstype : fstypes) {
671 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
672 nullptr);
673 if (rc == 0)
674 return true;
675
676 PLOG(WARNING) << "Unable to mount destination device " << device
677 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000678 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800679 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
680 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000681}
682
683bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700684 for (int num_retries = 0; ; ++num_retries) {
685 if (umount(mountpoint.c_str()) == 0)
686 break;
687
688 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
689 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700690 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700691 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000692 return true;
693}
694
Alex Deymof329b932014-10-30 01:37:48 -0700695bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700696 int* out_block_count,
697 int* out_block_size) {
698 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700699 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700700 ScopedFdCloser fd_closer(&fd);
701 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
702}
703
704bool GetFilesystemSizeFromFD(int fd,
705 int* out_block_count,
706 int* out_block_size) {
707 TEST_AND_RETURN_FALSE(fd >= 0);
708
Alex Deymo192393b2014-11-10 15:58:38 -0800709 // Determine the filesystem size by directly reading the block count and
710 // block size information from the superblock. Supported FS are ext3 and
711 // squashfs.
712
713 // Read from the fd only once and detect in memory. The first 2 KiB is enough
714 // to read the ext2 superblock (located at offset 1024) and the squashfs
715 // superblock (located at offset 0).
716 const ssize_t kBufferSize = 2048;
717
718 uint8_t buffer[kBufferSize];
719 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
720 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700721 return false;
722 }
Alex Deymo192393b2014-11-10 15:58:38 -0800723
724 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
725 return true;
726 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
727 return true;
728
729 LOG(ERROR) << "Unable to determine file system type.";
730 return false;
731}
732
733bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
734 int* out_block_count,
735 int* out_block_size) {
736 // See include/linux/ext2_fs.h for more details on the structure. We obtain
737 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
738 // library.
739 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
740 return false;
741
742 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
743
744 // ext3_fs.h: ext3_super_block.s_blocks_count
745 uint32_t block_count =
746 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
747
748 // ext3_fs.h: ext3_super_block.s_log_block_size
749 uint32_t log_block_size =
750 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
751
752 // ext3_fs.h: ext3_super_block.s_magic
753 uint16_t magic =
754 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
755
Darin Petkovd3f8c892010-10-12 21:38:45 -0700756 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800757 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700758 magic = le16toh(magic);
759
760 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800761 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
762 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
763 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700764 TEST_AND_RETURN_FALSE(block_count > 0);
765
Alex Deymo192393b2014-11-10 15:58:38 -0800766 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700767 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800768 if (out_block_size)
769 *out_block_size = 1 << log_block_size;
770 return true;
771}
772
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800773bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800774 int* out_block_count,
775 int* out_block_size) {
776 // See fs/squashfs/squashfs_fs.h for format details. We only support
777 // Squashfs 4.x little endian.
778
779 // sizeof(struct squashfs_super_block)
780 const size_t kSquashfsSuperBlockSize = 96;
781 if (buffer_size < kSquashfsSuperBlockSize)
782 return false;
783
784 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
785 if (memcmp(buffer, "hsqs", 4) != 0)
786 return false; // Only little endian is supported.
787
788 // squashfs_fs.h: struct squashfs_super_block.s_major
789 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
790 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
791
792 if (s_major != 4) {
793 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
794 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700795 }
Alex Deymo192393b2014-11-10 15:58:38 -0800796
797 // squashfs_fs.h: struct squashfs_super_block.bytes_used
798 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
799 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
800
801 const int block_size = 4096;
802
803 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
804 // so we round up to the nearest blocksize.
805 if (out_block_count)
806 *out_block_count = (bytes_used + block_size - 1) / block_size;
807 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700808 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700809 return true;
810}
811
Alex Deymo60ca1a72015-06-18 18:19:15 -0700812bool IsExtFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700813 chromeos::Blob header;
814 // The first 2 KiB is enough to read the ext2 superblock (located at offset
815 // 1024).
816 if (!ReadFileChunk(device, 0, 2048, &header))
817 return false;
818 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
819}
820
Alex Deymo60ca1a72015-06-18 18:19:15 -0700821bool IsSquashfsFilesystem(const string& device) {
Alex Deymode942f32015-03-13 11:57:15 -0700822 chromeos::Blob header;
823 // The first 96 is enough to read the squashfs superblock.
824 const ssize_t kSquashfsSuperBlockSize = 96;
825 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
826 return false;
827 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
828}
829
Alex Deymo032e7722014-03-25 17:53:56 -0700830// Tries to parse the header of an ELF file to obtain a human-readable
831// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800832static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
833 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700834 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700835 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700836 return false;
837 *output = "ELF";
838
839 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700840 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700841 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700842 switch (buffer[EI_CLASS]) {
843 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700844 *output += " 32-bit";
845 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700846 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700847 *output += " 64-bit";
848 break;
849 default:
850 *output += " ?-bit";
851 }
852
853 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700854 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700855 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800856 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700857 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700858 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700859 *output += " little-endian";
860 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700861 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700862 *output += " big-endian";
863 break;
864 default:
865 *output += " ?-endian";
866 // Don't parse anything after the 0x10 offset if endianness is unknown.
867 return true;
868 }
869
Alex Deymoc1711e22014-08-08 13:16:23 -0700870 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
871 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
872 // and size is the same for both 32 and 64 bits.
873 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700874 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700875 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700876 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700877 if (ei_data == ELFDATA2LSB)
878 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700879 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700880 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700881
882 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700883 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700884 *output += " x86";
885 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700886 case EM_MIPS:
887 *output += " mips";
888 break;
889 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700890 *output += " arm";
891 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700892 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700893 *output += " x86-64";
894 break;
895 default:
896 *output += " unknown-arch";
897 }
898 return true;
899}
900
901string GetFileFormat(const string& path) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800902 chromeos::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700903 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
904 return "File not found.";
905
906 string result;
907 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
908 return result;
909
910 return "data";
911}
912
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800913namespace {
914// Do the actual trigger. We do it as a main-loop callback to (try to) get a
915// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700916void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800917 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700918 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800919 if (pid == 0) {
920 // We are the child. Crash.
921 abort(); // never returns
922 }
923 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700924 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800925 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800926}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700927} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800928
929void ScheduleCrashReporterUpload() {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700930 chromeos::MessageLoop::current()->PostTask(
931 FROM_HERE,
932 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800933}
934
Chris Sosa4f8ee272012-11-30 13:01:54 -0800935bool SetCpuShares(CpuShares shares) {
936 string string_shares = base::IntToString(static_cast<int>(shares));
937 string cpu_shares_file = string(utils::kCGroupDir) + "/cpu.shares";
938 LOG(INFO) << "Setting cgroup cpu shares to " << string_shares;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700939 if (utils::WriteFile(cpu_shares_file.c_str(), string_shares.c_str(),
940 string_shares.size())) {
Chris Sosa4f8ee272012-11-30 13:01:54 -0800941 return true;
942 } else {
943 LOG(ERROR) << "Failed to change cgroup cpu shares to "<< string_shares
944 << " using " << cpu_shares_file;
945 return false;
946 }
Darin Petkovc6c135c2010-08-11 13:36:18 -0700947}
948
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700949int FuzzInt(int value, unsigned int range) {
950 int min = value - range / 2;
951 int max = value + range - range / 2;
952 return base::RandInt(min, max);
953}
954
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700955string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800956 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700957}
958
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800959string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400960 string str;
961
962 // Handle negative durations by prefixing with a minus.
963 if (delta.ToInternalValue() < 0) {
964 delta *= -1;
965 str = "-";
966 }
967
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700968 // Canonicalize into days, hours, minutes, seconds and microseconds.
969 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800970 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700971 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800972 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700973 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800974 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700975 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800976 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700977 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800978
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700979 if (days)
980 base::StringAppendF(&str, "%ud", days);
981 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800982 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700983 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800984 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700985 base::StringAppendF(&str, "%u", secs);
986 if (usecs) {
987 int width = 6;
988 while ((usecs / 10) * 10 == usecs) {
989 usecs /= 10;
990 width--;
991 }
992 base::StringAppendF(&str, ".%0*u", width, usecs);
993 }
994 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800995 return str;
996}
997
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700998string ToString(const Time utc_time) {
999 Time::Exploded exp_time;
1000 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -07001001 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001002 exp_time.month,
1003 exp_time.day_of_month,
1004 exp_time.year,
1005 exp_time.hour,
1006 exp_time.minute,
1007 exp_time.second);
1008}
adlr@google.com3defe6a2009-12-04 20:57:17 +00001009
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001010string ToString(bool b) {
1011 return (b ? "true" : "false");
1012}
1013
Alex Deymo1c656c42013-06-28 11:02:14 -07001014string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -07001015 switch (source) {
1016 case kDownloadSourceHttpsServer: return "HttpsServer";
1017 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -07001018 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -07001019 case kNumDownloadSources: return "Unknown";
1020 // Don't add a default case to let the compiler warn about newly added
1021 // download sources which should be added here.
1022 }
1023
1024 return "Unknown";
1025}
1026
Alex Deymo1c656c42013-06-28 11:02:14 -07001027string ToString(PayloadType payload_type) {
1028 switch (payload_type) {
1029 case kPayloadTypeDelta: return "Delta";
1030 case kPayloadTypeFull: return "Full";
1031 case kPayloadTypeForcedFull: return "ForcedFull";
1032 case kNumPayloadTypes: return "Unknown";
1033 // Don't add a default case to let the compiler warn about newly added
1034 // payload types which should be added here.
1035 }
1036
1037 return "Unknown";
1038}
1039
David Zeuthena99981f2013-04-29 13:42:47 -07001040ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001041 // Ignore the higher order bits in the code by applying the mask as
1042 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001043 // with values less than ErrorCode::kUmaReportedMax.
1044 ErrorCode base_code = static_cast<ErrorCode>(
1045 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -07001046
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001047 // Make additional adjustments required for UMA and error classification.
1048 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
1049 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001050 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -07001051 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001052 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001053 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001054 << " to ErrorCode::kOmahaErrorInHTTPResponse";
1055 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001056 }
1057
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001058 return base_code;
1059}
1060
David Zeuthen33bae492014-02-25 16:16:18 -08001061metrics::AttemptResult GetAttemptResult(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001062 ErrorCode base_code = static_cast<ErrorCode>(
1063 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001064
1065 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001066 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001067 return metrics::AttemptResult::kUpdateSucceeded;
1068
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001069 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001070 return metrics::AttemptResult::kPayloadDownloadError;
1071
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001072 case ErrorCode::kDownloadInvalidMetadataSize:
1073 case ErrorCode::kDownloadInvalidMetadataMagicString:
1074 case ErrorCode::kDownloadMetadataSignatureError:
1075 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1076 case ErrorCode::kPayloadMismatchedType:
1077 case ErrorCode::kUnsupportedMajorPayloadVersion:
1078 case ErrorCode::kUnsupportedMinorPayloadVersion:
1079 case ErrorCode::kDownloadNewPartitionInfoError:
1080 case ErrorCode::kDownloadSignatureMissingInManifest:
1081 case ErrorCode::kDownloadManifestParseError:
1082 case ErrorCode::kDownloadOperationHashMissingError:
David Zeuthen33bae492014-02-25 16:16:18 -08001083 return metrics::AttemptResult::kMetadataMalformed;
1084
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001085 case ErrorCode::kDownloadOperationHashMismatch:
1086 case ErrorCode::kDownloadOperationHashVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001087 return metrics::AttemptResult::kOperationMalformed;
1088
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001089 case ErrorCode::kDownloadOperationExecutionError:
1090 case ErrorCode::kInstallDeviceOpenError:
1091 case ErrorCode::kKernelDeviceOpenError:
1092 case ErrorCode::kDownloadWriteError:
1093 case ErrorCode::kFilesystemCopierError:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001094 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001095 return metrics::AttemptResult::kOperationExecutionError;
1096
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001097 case ErrorCode::kDownloadMetadataSignatureMismatch:
David Zeuthen33bae492014-02-25 16:16:18 -08001098 return metrics::AttemptResult::kMetadataVerificationFailed;
1099
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001100 case ErrorCode::kPayloadSizeMismatchError:
1101 case ErrorCode::kPayloadHashMismatchError:
1102 case ErrorCode::kDownloadPayloadVerificationError:
1103 case ErrorCode::kSignedDeltaPayloadExpectedError:
1104 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001105 return metrics::AttemptResult::kPayloadVerificationFailed;
1106
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001107 case ErrorCode::kNewRootfsVerificationError:
1108 case ErrorCode::kNewKernelVerificationError:
David Zeuthen33bae492014-02-25 16:16:18 -08001109 return metrics::AttemptResult::kVerificationFailed;
1110
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001111 case ErrorCode::kPostinstallRunnerError:
1112 case ErrorCode::kPostinstallBootedFromFirmwareB:
1113 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
David Zeuthen33bae492014-02-25 16:16:18 -08001114 return metrics::AttemptResult::kPostInstallFailed;
1115
1116 // We should never get these errors in the update-attempt stage so
1117 // return internal error if this happens.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001118 case ErrorCode::kError:
1119 case ErrorCode::kOmahaRequestXMLParseError:
1120 case ErrorCode::kOmahaRequestError:
1121 case ErrorCode::kOmahaResponseHandlerError:
1122 case ErrorCode::kDownloadStateInitializationError:
1123 case ErrorCode::kOmahaRequestEmptyResponseError:
1124 case ErrorCode::kDownloadInvalidMetadataSignature:
1125 case ErrorCode::kOmahaResponseInvalid:
1126 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1127 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1128 case ErrorCode::kOmahaErrorInHTTPResponse:
1129 case ErrorCode::kDownloadMetadataSignatureMissingError:
1130 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1131 case ErrorCode::kPostinstallPowerwashError:
1132 case ErrorCode::kUpdateCanceledByChannelChange:
David Zeuthenf3e28012014-08-26 18:23:52 -04001133 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
David Zeuthen33bae492014-02-25 16:16:18 -08001134 return metrics::AttemptResult::kInternalError;
1135
1136 // Special flags. These can't happen (we mask them out above) but
1137 // the compiler doesn't know that. Just break out so we can warn and
1138 // return |kInternalError|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001139 case ErrorCode::kUmaReportedMax:
1140 case ErrorCode::kOmahaRequestHTTPResponseBase:
1141 case ErrorCode::kDevModeFlag:
1142 case ErrorCode::kResumedFlag:
1143 case ErrorCode::kTestImageFlag:
1144 case ErrorCode::kTestOmahaUrlFlag:
1145 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001146 break;
1147 }
1148
1149 LOG(ERROR) << "Unexpected error code " << base_code;
1150 return metrics::AttemptResult::kInternalError;
1151}
1152
1153
1154metrics::DownloadErrorCode GetDownloadErrorCode(ErrorCode code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001155 ErrorCode base_code = static_cast<ErrorCode>(
1156 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
David Zeuthen33bae492014-02-25 16:16:18 -08001157
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001158 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
1159 int http_status =
1160 static_cast<int>(base_code) -
1161 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase);
David Zeuthen33bae492014-02-25 16:16:18 -08001162 if (http_status >= 200 && http_status <= 599) {
1163 return static_cast<metrics::DownloadErrorCode>(
1164 static_cast<int>(metrics::DownloadErrorCode::kHttpStatus200) +
1165 http_status - 200);
1166 } else if (http_status == 0) {
1167 // The code is using HTTP Status 0 for "Unable to get http
1168 // response code."
1169 return metrics::DownloadErrorCode::kDownloadError;
1170 }
1171 LOG(WARNING) << "Unexpected HTTP status code " << http_status;
1172 return metrics::DownloadErrorCode::kHttpStatusOther;
1173 }
1174
1175 switch (base_code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001176 // Unfortunately, ErrorCode::kDownloadTransferError is returned for a wide
David Zeuthen33bae492014-02-25 16:16:18 -08001177 // variety of errors (proxy errors, host not reachable, timeouts etc.).
1178 //
1179 // For now just map that to kDownloading. See http://crbug.com/355745
1180 // for how we plan to add more detail in the future.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001181 case ErrorCode::kDownloadTransferError:
David Zeuthen33bae492014-02-25 16:16:18 -08001182 return metrics::DownloadErrorCode::kDownloadError;
1183
1184 // All of these error codes are not related to downloading so break
1185 // out so we can warn and return InputMalformed.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001186 case ErrorCode::kSuccess:
1187 case ErrorCode::kError:
1188 case ErrorCode::kOmahaRequestError:
1189 case ErrorCode::kOmahaResponseHandlerError:
1190 case ErrorCode::kFilesystemCopierError:
1191 case ErrorCode::kPostinstallRunnerError:
1192 case ErrorCode::kPayloadMismatchedType:
1193 case ErrorCode::kInstallDeviceOpenError:
1194 case ErrorCode::kKernelDeviceOpenError:
1195 case ErrorCode::kPayloadHashMismatchError:
1196 case ErrorCode::kPayloadSizeMismatchError:
1197 case ErrorCode::kDownloadPayloadVerificationError:
1198 case ErrorCode::kDownloadNewPartitionInfoError:
1199 case ErrorCode::kDownloadWriteError:
1200 case ErrorCode::kNewRootfsVerificationError:
1201 case ErrorCode::kNewKernelVerificationError:
1202 case ErrorCode::kSignedDeltaPayloadExpectedError:
1203 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1204 case ErrorCode::kPostinstallBootedFromFirmwareB:
1205 case ErrorCode::kDownloadStateInitializationError:
1206 case ErrorCode::kDownloadInvalidMetadataMagicString:
1207 case ErrorCode::kDownloadSignatureMissingInManifest:
1208 case ErrorCode::kDownloadManifestParseError:
1209 case ErrorCode::kDownloadMetadataSignatureError:
1210 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1211 case ErrorCode::kDownloadMetadataSignatureMismatch:
1212 case ErrorCode::kDownloadOperationHashVerificationError:
1213 case ErrorCode::kDownloadOperationExecutionError:
1214 case ErrorCode::kDownloadOperationHashMismatch:
1215 case ErrorCode::kOmahaRequestEmptyResponseError:
1216 case ErrorCode::kOmahaRequestXMLParseError:
1217 case ErrorCode::kDownloadInvalidMetadataSize:
1218 case ErrorCode::kDownloadInvalidMetadataSignature:
1219 case ErrorCode::kOmahaResponseInvalid:
1220 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1221 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1222 case ErrorCode::kOmahaErrorInHTTPResponse:
1223 case ErrorCode::kDownloadOperationHashMissingError:
1224 case ErrorCode::kDownloadMetadataSignatureMissingError:
1225 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1226 case ErrorCode::kPostinstallPowerwashError:
1227 case ErrorCode::kUpdateCanceledByChannelChange:
1228 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1229 case ErrorCode::kUnsupportedMajorPayloadVersion:
1230 case ErrorCode::kUnsupportedMinorPayloadVersion:
David Zeuthenf3e28012014-08-26 18:23:52 -04001231 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
Allie Woodeb9e6d82015-04-17 13:55:30 -07001232 case ErrorCode::kFilesystemVerifierError:
David Zeuthen33bae492014-02-25 16:16:18 -08001233 break;
1234
1235 // Special flags. These can't happen (we mask them out above) but
1236 // the compiler doesn't know that. Just break out so we can warn and
1237 // return |kInputMalformed|.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001238 case ErrorCode::kUmaReportedMax:
1239 case ErrorCode::kOmahaRequestHTTPResponseBase:
1240 case ErrorCode::kDevModeFlag:
1241 case ErrorCode::kResumedFlag:
1242 case ErrorCode::kTestImageFlag:
1243 case ErrorCode::kTestOmahaUrlFlag:
1244 case ErrorCode::kSpecialFlags:
David Zeuthen33bae492014-02-25 16:16:18 -08001245 LOG(ERROR) << "Unexpected error code " << base_code;
1246 break;
1247 }
1248
1249 return metrics::DownloadErrorCode::kInputMalformed;
1250}
1251
David Zeuthenb281f072014-04-02 10:20:19 -07001252metrics::ConnectionType GetConnectionType(
1253 NetworkConnectionType type,
1254 NetworkTethering tethering) {
1255 switch (type) {
Alex Deymo75eac7e2015-07-29 13:39:14 -07001256 case NetworkConnectionType::kUnknown:
David Zeuthenb281f072014-04-02 10:20:19 -07001257 return metrics::ConnectionType::kUnknown;
1258
Alex Deymo75eac7e2015-07-29 13:39:14 -07001259 case NetworkConnectionType::kEthernet:
David Zeuthenb281f072014-04-02 10:20:19 -07001260 if (tethering == NetworkTethering::kConfirmed)
1261 return metrics::ConnectionType::kTetheredEthernet;
1262 else
1263 return metrics::ConnectionType::kEthernet;
1264
Alex Deymo75eac7e2015-07-29 13:39:14 -07001265 case NetworkConnectionType::kWifi:
David Zeuthenb281f072014-04-02 10:20:19 -07001266 if (tethering == NetworkTethering::kConfirmed)
1267 return metrics::ConnectionType::kTetheredWifi;
1268 else
1269 return metrics::ConnectionType::kWifi;
1270
Alex Deymo75eac7e2015-07-29 13:39:14 -07001271 case NetworkConnectionType::kWimax:
David Zeuthenb281f072014-04-02 10:20:19 -07001272 return metrics::ConnectionType::kWimax;
1273
Alex Deymo75eac7e2015-07-29 13:39:14 -07001274 case NetworkConnectionType::kBluetooth:
David Zeuthenb281f072014-04-02 10:20:19 -07001275 return metrics::ConnectionType::kBluetooth;
1276
Alex Deymo75eac7e2015-07-29 13:39:14 -07001277 case NetworkConnectionType::kCellular:
David Zeuthenb281f072014-04-02 10:20:19 -07001278 return metrics::ConnectionType::kCellular;
1279 }
1280
Alex Deymo75eac7e2015-07-29 13:39:14 -07001281 LOG(ERROR) << "Unexpected network connection type: type="
1282 << static_cast<int>(type)
David Zeuthenb281f072014-04-02 10:20:19 -07001283 << ", tethering=" << static_cast<int>(tethering);
1284
1285 return metrics::ConnectionType::kUnknown;
1286}
1287
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001288// Returns a printable version of the various flags denoted in the higher order
1289// bits of the given code. Returns an empty string if none of those bits are
1290// set.
1291string GetFlagNames(uint32_t code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001292 uint32_t flags = (static_cast<uint32_t>(code) &
1293 static_cast<uint32_t>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001294 string flag_names;
1295 string separator = "";
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001296 for (size_t i = 0; i < sizeof(flags) * 8; i++) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001297 uint32_t flag = flags & (1 << i);
1298 if (flag) {
David Zeuthena99981f2013-04-29 13:42:47 -07001299 flag_names += separator + CodeToString(static_cast<ErrorCode>(flag));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001300 separator = ", ";
1301 }
1302 }
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001303
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001304 return flag_names;
Jay Srinivasanf0572052012-10-23 18:12:56 -07001305}
1306
David Zeuthena99981f2013-04-29 13:42:47 -07001307void SendErrorCodeToUma(SystemState* system_state, ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001308 if (!system_state)
1309 return;
1310
David Zeuthena99981f2013-04-29 13:42:47 -07001311 ErrorCode uma_error_code = GetBaseErrorCode(code);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001312
1313 // If the code doesn't have flags computed already, compute them now based on
1314 // the state of the current update attempt.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001315 uint32_t flags =
1316 static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags);
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001317 if (!flags)
1318 flags = system_state->update_attempter()->GetErrorCodeFlags();
1319
1320 // Determine the UMA bucket depending on the flags. But, ignore the resumed
1321 // flag, as it's perfectly normal for production devices to resume their
1322 // downloads and so we want to record those cases also in NormalErrorCodes
1323 // bucket.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001324 string metric =
1325 flags & ~static_cast<uint32_t>(ErrorCode::kResumedFlag) ?
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001326 "Installer.DevModeErrorCodes" : "Installer.NormalErrorCodes";
1327
1328 LOG(INFO) << "Sending error code " << uma_error_code
1329 << " (" << CodeToString(uma_error_code) << ")"
1330 << " to UMA metric: " << metric
1331 << ". Flags = " << (flags ? GetFlagNames(flags) : "None");
1332
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001333 system_state->metrics_lib()->SendEnumToUMA(
1334 metric, static_cast<int>(uma_error_code),
1335 static_cast<int>(ErrorCode::kUmaReportedMax));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001336}
1337
David Zeuthena99981f2013-04-29 13:42:47 -07001338string CodeToString(ErrorCode code) {
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001339 // If the given code has both parts (i.e. the error code part and the flags
1340 // part) then strip off the flags part since the switch statement below
1341 // has case statements only for the base error code or a single flag but
1342 // doesn't support any combinations of those.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001343 if ((static_cast<int>(code) & static_cast<int>(ErrorCode::kSpecialFlags)) &&
1344 (static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags)))
1345 code = static_cast<ErrorCode>(
1346 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001347 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001348 case ErrorCode::kSuccess: return "ErrorCode::kSuccess";
1349 case ErrorCode::kError: return "ErrorCode::kError";
1350 case ErrorCode::kOmahaRequestError: return "ErrorCode::kOmahaRequestError";
1351 case ErrorCode::kOmahaResponseHandlerError:
1352 return "ErrorCode::kOmahaResponseHandlerError";
1353 case ErrorCode::kFilesystemCopierError:
1354 return "ErrorCode::kFilesystemCopierError";
1355 case ErrorCode::kPostinstallRunnerError:
1356 return "ErrorCode::kPostinstallRunnerError";
1357 case ErrorCode::kPayloadMismatchedType:
1358 return "ErrorCode::kPayloadMismatchedType";
1359 case ErrorCode::kInstallDeviceOpenError:
1360 return "ErrorCode::kInstallDeviceOpenError";
1361 case ErrorCode::kKernelDeviceOpenError:
1362 return "ErrorCode::kKernelDeviceOpenError";
1363 case ErrorCode::kDownloadTransferError:
1364 return "ErrorCode::kDownloadTransferError";
1365 case ErrorCode::kPayloadHashMismatchError:
1366 return "ErrorCode::kPayloadHashMismatchError";
1367 case ErrorCode::kPayloadSizeMismatchError:
1368 return "ErrorCode::kPayloadSizeMismatchError";
1369 case ErrorCode::kDownloadPayloadVerificationError:
1370 return "ErrorCode::kDownloadPayloadVerificationError";
1371 case ErrorCode::kDownloadNewPartitionInfoError:
1372 return "ErrorCode::kDownloadNewPartitionInfoError";
1373 case ErrorCode::kDownloadWriteError:
1374 return "ErrorCode::kDownloadWriteError";
1375 case ErrorCode::kNewRootfsVerificationError:
1376 return "ErrorCode::kNewRootfsVerificationError";
1377 case ErrorCode::kNewKernelVerificationError:
1378 return "ErrorCode::kNewKernelVerificationError";
1379 case ErrorCode::kSignedDeltaPayloadExpectedError:
1380 return "ErrorCode::kSignedDeltaPayloadExpectedError";
1381 case ErrorCode::kDownloadPayloadPubKeyVerificationError:
1382 return "ErrorCode::kDownloadPayloadPubKeyVerificationError";
1383 case ErrorCode::kPostinstallBootedFromFirmwareB:
1384 return "ErrorCode::kPostinstallBootedFromFirmwareB";
1385 case ErrorCode::kDownloadStateInitializationError:
1386 return "ErrorCode::kDownloadStateInitializationError";
1387 case ErrorCode::kDownloadInvalidMetadataMagicString:
1388 return "ErrorCode::kDownloadInvalidMetadataMagicString";
1389 case ErrorCode::kDownloadSignatureMissingInManifest:
1390 return "ErrorCode::kDownloadSignatureMissingInManifest";
1391 case ErrorCode::kDownloadManifestParseError:
1392 return "ErrorCode::kDownloadManifestParseError";
1393 case ErrorCode::kDownloadMetadataSignatureError:
1394 return "ErrorCode::kDownloadMetadataSignatureError";
1395 case ErrorCode::kDownloadMetadataSignatureVerificationError:
1396 return "ErrorCode::kDownloadMetadataSignatureVerificationError";
1397 case ErrorCode::kDownloadMetadataSignatureMismatch:
1398 return "ErrorCode::kDownloadMetadataSignatureMismatch";
1399 case ErrorCode::kDownloadOperationHashVerificationError:
1400 return "ErrorCode::kDownloadOperationHashVerificationError";
1401 case ErrorCode::kDownloadOperationExecutionError:
1402 return "ErrorCode::kDownloadOperationExecutionError";
1403 case ErrorCode::kDownloadOperationHashMismatch:
1404 return "ErrorCode::kDownloadOperationHashMismatch";
1405 case ErrorCode::kOmahaRequestEmptyResponseError:
1406 return "ErrorCode::kOmahaRequestEmptyResponseError";
1407 case ErrorCode::kOmahaRequestXMLParseError:
1408 return "ErrorCode::kOmahaRequestXMLParseError";
1409 case ErrorCode::kDownloadInvalidMetadataSize:
1410 return "ErrorCode::kDownloadInvalidMetadataSize";
1411 case ErrorCode::kDownloadInvalidMetadataSignature:
1412 return "ErrorCode::kDownloadInvalidMetadataSignature";
1413 case ErrorCode::kOmahaResponseInvalid:
1414 return "ErrorCode::kOmahaResponseInvalid";
1415 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1416 return "ErrorCode::kOmahaUpdateIgnoredPerPolicy";
1417 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1418 return "ErrorCode::kOmahaUpdateDeferredPerPolicy";
1419 case ErrorCode::kOmahaErrorInHTTPResponse:
1420 return "ErrorCode::kOmahaErrorInHTTPResponse";
1421 case ErrorCode::kDownloadOperationHashMissingError:
1422 return "ErrorCode::kDownloadOperationHashMissingError";
1423 case ErrorCode::kDownloadMetadataSignatureMissingError:
1424 return "ErrorCode::kDownloadMetadataSignatureMissingError";
1425 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1426 return "ErrorCode::kOmahaUpdateDeferredForBackoff";
1427 case ErrorCode::kPostinstallPowerwashError:
1428 return "ErrorCode::kPostinstallPowerwashError";
1429 case ErrorCode::kUpdateCanceledByChannelChange:
1430 return "ErrorCode::kUpdateCanceledByChannelChange";
1431 case ErrorCode::kUmaReportedMax:
1432 return "ErrorCode::kUmaReportedMax";
1433 case ErrorCode::kOmahaRequestHTTPResponseBase:
1434 return "ErrorCode::kOmahaRequestHTTPResponseBase";
1435 case ErrorCode::kResumedFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001436 return "Resumed";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001437 case ErrorCode::kDevModeFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001438 return "DevMode";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001439 case ErrorCode::kTestImageFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001440 return "TestImage";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001441 case ErrorCode::kTestOmahaUrlFlag:
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001442 return "TestOmahaUrl";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001443 case ErrorCode::kSpecialFlags:
1444 return "ErrorCode::kSpecialFlags";
1445 case ErrorCode::kPostinstallFirmwareRONotUpdatable:
1446 return "ErrorCode::kPostinstallFirmwareRONotUpdatable";
1447 case ErrorCode::kUnsupportedMajorPayloadVersion:
1448 return "ErrorCode::kUnsupportedMajorPayloadVersion";
1449 case ErrorCode::kUnsupportedMinorPayloadVersion:
1450 return "ErrorCode::kUnsupportedMinorPayloadVersion";
David Zeuthenf3e28012014-08-26 18:23:52 -04001451 case ErrorCode::kOmahaRequestXMLHasEntityDecl:
1452 return "ErrorCode::kOmahaRequestXMLHasEntityDecl";
Allie Woodeb9e6d82015-04-17 13:55:30 -07001453 case ErrorCode::kFilesystemVerifierError:
1454 return "ErrorCode::kFilesystemVerifierError";
Jay Srinivasan55f50c22013-01-10 19:24:35 -08001455 // Don't add a default case to let the compiler warn about newly added
1456 // error codes which should be added here.
1457 }
1458
1459 return "Unknown error: " + base::UintToString(static_cast<unsigned>(code));
1460}
Jay Srinivasanf0572052012-10-23 18:12:56 -07001461
Gilad Arnold30dedd82013-07-03 06:19:09 -07001462bool CreatePowerwashMarkerFile(const char* file_path) {
1463 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1464 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001465 kPowerwashCommand,
1466 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001467 if (result) {
1468 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1469 } else {
1470 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1471 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001472
1473 return result;
1474}
1475
Gilad Arnold30dedd82013-07-03 06:19:09 -07001476bool DeletePowerwashMarkerFile(const char* file_path) {
1477 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001478 const base::FilePath kPowerwashMarkerPath(marker_file);
1479 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001480
1481 if (result)
1482 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001483 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001484 else
1485 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001486 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001487
1488 return result;
1489}
1490
Alex Deymof329b932014-10-30 01:37:48 -07001491bool GetInstallDev(const string& boot_dev, string* install_dev) {
1492 string disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001493 int partition_num;
1494 if (!SplitPartitionName(boot_dev, &disk_name, &partition_num))
1495 return false;
Liam McLoughlin049d1652013-07-31 18:47:46 -07001496
Chris Sosad317e402013-06-12 13:47:09 -07001497 // Right now, we just switch '3' and '5' partition numbers.
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -07001498 if (partition_num == 3) {
1499 partition_num = 5;
1500 } else if (partition_num == 5) {
1501 partition_num = 3;
1502 } else {
1503 return false;
1504 }
1505
1506 if (install_dev)
1507 *install_dev = MakePartitionName(disk_name, partition_num);
Liam McLoughlin049d1652013-07-31 18:47:46 -07001508
Chris Sosad317e402013-06-12 13:47:09 -07001509 return true;
1510}
1511
David Zeuthen27a48bc2013-08-06 12:06:29 -07001512Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001513 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1514 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001515 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1516}
1517
Alex Deymof329b932014-10-30 01:37:48 -07001518string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001519 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001520 for (vector<string>::const_iterator i = vec_str.begin();
1521 i != vec_str.end(); ++i) {
1522 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001523 str += ", ";
1524 str += '"';
1525 str += *i;
1526 str += '"';
1527 }
1528 str += "]";
1529 return str;
1530}
1531
David Zeuthen8f191b22013-08-06 12:27:50 -07001532string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001533 string encoded_hash = chromeos::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -07001534 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001535 payload_size,
1536 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001537}
1538
Alex Deymof329b932014-10-30 01:37:48 -07001539bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001540 base::FilePath *out_path) {
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001541 chromeos::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001542
1543 out_path->clear();
1544
1545 if (base64_encoded.size() == 0) {
1546 LOG(ERROR) << "Can't decode empty string.";
1547 return false;
1548 }
1549
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001550 if (!chromeos::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001551 contents.size() == 0) {
1552 LOG(ERROR) << "Error decoding base64.";
1553 return false;
1554 }
1555
Alex Vakulenko75039d72014-03-25 12:36:28 -07001556 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001557 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001558 LOG(ERROR) << "Error creating temporary file.";
1559 return false;
1560 }
1561
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001562 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001563 PLOG(ERROR) << "Error writing to temporary file.";
1564 if (fclose(file) != 0)
1565 PLOG(ERROR) << "Error closing temporary file.";
1566 if (unlink(out_path->value().c_str()) != 0)
1567 PLOG(ERROR) << "Error unlinking temporary file.";
1568 out_path->clear();
1569 return false;
1570 }
1571
1572 if (fclose(file) != 0) {
1573 PLOG(ERROR) << "Error closing temporary file.";
1574 out_path->clear();
1575 return false;
1576 }
1577
1578 return true;
1579}
1580
Alex Deymof329b932014-10-30 01:37:48 -07001581bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001582 time_t unix_time = time.ToTimeT();
1583 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1584 const time_t kOmahaEpoch = 1167638400;
1585 const int64_t kNumSecondsPerWeek = 7*24*3600;
1586 const int64_t kNumDaysPerWeek = 7;
1587
1588 time_t omaha_time = unix_time - kOmahaEpoch;
1589
1590 if (omaha_time < 0)
1591 return false;
1592
1593 // Note, as per the comment in utils.h we are deliberately not
1594 // handling DST correctly.
1595
1596 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1597 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1598
1599 return true;
1600}
1601
David Zeuthen33bae492014-02-25 16:16:18 -08001602bool WallclockDurationHelper(SystemState* system_state,
Alex Deymof329b932014-10-30 01:37:48 -07001603 const string& state_variable_key,
1604 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001605 bool ret = false;
1606
Alex Deymof329b932014-10-30 01:37:48 -07001607 Time now = system_state->clock()->GetWallclockTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001608 int64_t stored_value;
1609 if (system_state->prefs()->GetInt64(state_variable_key, &stored_value)) {
Alex Deymof329b932014-10-30 01:37:48 -07001610 Time stored_time = Time::FromInternalValue(stored_value);
David Zeuthen33bae492014-02-25 16:16:18 -08001611 if (stored_time > now) {
1612 LOG(ERROR) << "Stored time-stamp used for " << state_variable_key
1613 << " is in the future.";
1614 } else {
1615 *out_duration = now - stored_time;
1616 ret = true;
1617 }
1618 }
1619
1620 if (!system_state->prefs()->SetInt64(state_variable_key,
1621 now.ToInternalValue())) {
1622 LOG(ERROR) << "Error storing time-stamp in " << state_variable_key;
1623 }
1624
1625 return ret;
1626}
1627
1628bool MonotonicDurationHelper(SystemState* system_state,
1629 int64_t* storage,
Alex Deymof329b932014-10-30 01:37:48 -07001630 TimeDelta* out_duration) {
David Zeuthen33bae492014-02-25 16:16:18 -08001631 bool ret = false;
1632
Alex Deymof329b932014-10-30 01:37:48 -07001633 Time now = system_state->clock()->GetMonotonicTime();
David Zeuthen33bae492014-02-25 16:16:18 -08001634 if (*storage != 0) {
Alex Deymof329b932014-10-30 01:37:48 -07001635 Time stored_time = Time::FromInternalValue(*storage);
David Zeuthen33bae492014-02-25 16:16:18 -08001636 *out_duration = now - stored_time;
1637 ret = true;
1638 }
1639 *storage = now.ToInternalValue();
1640
1641 return ret;
1642}
1643
Alex Deymob42b98d2015-07-06 17:42:38 -07001644bool GetMinorVersion(const chromeos::KeyValueStore& store,
1645 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001646 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001647 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001648 if (!base::StringToUint(result, minor_version)) {
1649 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1650 return false;
1651 }
Allie Wood78750a42015-02-11 15:42:11 -08001652 return true;
1653 }
1654 return false;
1655}
1656
Alex Deymo60ca1a72015-06-18 18:19:15 -07001657bool ReadExtents(const string& path, const vector<Extent>& extents,
Allie Wood56873452015-03-27 17:48:40 -07001658 chromeos::Blob* out_data, ssize_t out_data_size,
1659 size_t block_size) {
1660 chromeos::Blob data(out_data_size);
1661 ssize_t bytes_read = 0;
1662 int fd = open(path.c_str(), O_RDONLY);
1663 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1664 ScopedFdCloser fd_closer(&fd);
1665
Gilad Arnold41e34742015-05-11 11:31:50 -07001666 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001667 ssize_t bytes_read_this_iteration = 0;
1668 ssize_t bytes = extent.num_blocks() * block_size;
1669 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1670 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1671 &data[bytes_read],
1672 bytes,
1673 extent.start_block() * block_size,
1674 &bytes_read_this_iteration));
1675 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1676 bytes_read += bytes_read_this_iteration;
1677 }
1678 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1679 *out_data = data;
1680 return true;
1681}
1682
adlr@google.com3defe6a2009-12-04 20:57:17 +00001683} // namespace utils
1684
1685} // namespace chromeos_update_engine