blob: 912bc966dcebe565d33c3bf2452bbb853db722ee [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
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/common/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>
Alex Deymo6f20dd42015-08-18 16:42:46 -070023#include <endian.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000024#include <errno.h>
Alex Deymo192393b2014-11-10 15:58:38 -080025#include <ext2fs/ext2fs.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080026#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000027#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070030#include <sys/mount.h>
31#include <sys/resource.h>
32#include <sys/stat.h>
33#include <sys/types.h>
34#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000035#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070036
adlr@google.com3defe6a2009-12-04 20:57:17 +000037#include <algorithm>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070038#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070039#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070040
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070041#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070042#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080043#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070044#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070045#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070046#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040047#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080048#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050049#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070050#include <base/strings/string_number_conversions.h>
51#include <base/strings/string_split.h>
52#include <base/strings/string_util.h>
53#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070054#include <brillo/data_encoding.h>
55#include <brillo/message_loops/message_loop.h>
Will Drewry8f71da82010-08-30 14:07:11 -050056
Alex Deymo39910dc2015-11-09 17:04:30 -080057#include "update_engine/common/clock_interface.h"
58#include "update_engine/common/constants.h"
Sen Jiang9c123462015-11-19 13:16:23 -080059#include "update_engine/common/platform_constants.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080060#include "update_engine/common/prefs_interface.h"
61#include "update_engine/common/subprocess.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080062#include "update_engine/payload_consumer/file_descriptor.h"
63#include "update_engine/payload_consumer/file_writer.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000064
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070065using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080066using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000067using std::min;
Chris Sosac1972482013-04-30 22:31:10 -070068using std::pair;
adlr@google.com3defe6a2009-12-04 20:57:17 +000069using std::string;
70using std::vector;
71
72namespace chromeos_update_engine {
73
Ben Chan77a1eba2012-10-07 22:54:55 -070074namespace {
75
76// The following constants control how UnmountFilesystem should retry if
77// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
78// one second.
79const int kUnmountMaxNumOfRetries = 5;
80const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070081
82// Number of bytes to read from a file to attempt to detect its contents. Used
83// in GetFileFormat.
84const int kGetFileFormatMaxHeaderSize = 32;
85
Alex Deymodd132f32015-09-14 19:12:07 -070086// The path to the kernel's boot_id.
87const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
88
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080089// Return true if |disk_name| is an MTD or a UBI device. Note that this test is
90// simply based on the name of the device.
91bool IsMtdDeviceName(const string& disk_name) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080092 return base::StartsWith(disk_name, "/dev/ubi",
93 base::CompareCase::SENSITIVE) ||
94 base::StartsWith(disk_name, "/dev/mtd", base::CompareCase::SENSITIVE);
Nam T. Nguyena78b28c2015-03-06 22:30:12 -080095}
96
97// Return the device name for the corresponding partition on a NAND device.
98// WARNING: This function returns device names that are not mountable.
99string MakeNandPartitionName(int partition_num) {
100 switch (partition_num) {
101 case 2:
102 case 4:
103 case 6: {
104 return base::StringPrintf("/dev/mtd%d", partition_num);
105 }
106 default: {
107 return base::StringPrintf("/dev/ubi%d_0", partition_num);
108 }
109 }
110}
111
112// Return the device name for the corresponding partition on a NAND device that
113// may be mountable (but may not be writable).
114string MakeNandPartitionNameForMount(int partition_num) {
115 switch (partition_num) {
116 case 2:
117 case 4:
118 case 6: {
119 return base::StringPrintf("/dev/mtd%d", partition_num);
120 }
121 case 3:
122 case 5:
123 case 7: {
124 return base::StringPrintf("/dev/ubiblock%d_0", partition_num);
125 }
126 default: {
127 return base::StringPrintf("/dev/ubi%d_0", partition_num);
128 }
129 }
130}
131
Alex Deymo5aa1c542015-09-18 01:02:33 -0700132// If |path| is absolute, or explicit relative to the current working directory,
133// leaves it as is. Otherwise, uses the system's temp directory, as defined by
134// base::GetTempDir() and prepends it to |path|. On success stores the full
135// temporary path in |template_path| and returns true.
136bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800137 if (path[0] == '/' ||
138 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
139 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700140 *template_path = base::FilePath(path);
141 return true;
142 }
143
144 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -0800145#ifdef __ANDROID__
146 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
147 if (!base::PathExists(temp_dir))
148 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
149#else
Alex Deymo5aa1c542015-09-18 01:02:33 -0700150 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Sen Jiang9c123462015-11-19 13:16:23 -0800151#endif // __ANDROID__
Alex Deymo5aa1c542015-09-18 01:02:33 -0700152 *template_path = temp_dir.Append(path);
153 return true;
154}
155
Ben Chan77a1eba2012-10-07 22:54:55 -0700156} // namespace
157
adlr@google.com3defe6a2009-12-04 20:57:17 +0000158namespace utils {
159
J. Richard Barnette63137e52013-10-28 10:57:29 -0700160string ParseECVersion(string input_line) {
Ben Chan736fcb52014-05-21 18:28:22 -0700161 base::TrimWhitespaceASCII(input_line, base::TRIM_ALL, &input_line);
Chris Sosac1972482013-04-30 22:31:10 -0700162
Alex Vakulenko75039d72014-03-25 12:36:28 -0700163 // At this point we want to convert the format key=value pair from mosys to
Chris Sosac1972482013-04-30 22:31:10 -0700164 // a vector of key value pairs.
Ben Chanf9cb98c2014-09-21 18:31:30 -0700165 vector<pair<string, string>> kv_pairs;
J. Richard Barnette63137e52013-10-28 10:57:29 -0700166 if (base::SplitStringIntoKeyValuePairs(input_line, '=', ' ', &kv_pairs)) {
Alex Deymo020600d2014-11-05 21:05:55 -0800167 for (const pair<string, string>& kv_pair : kv_pairs) {
Chris Sosac1972482013-04-30 22:31:10 -0700168 // Finally match against the fw_verion which may have quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800169 if (kv_pair.first == "fw_version") {
Chris Sosac1972482013-04-30 22:31:10 -0700170 string output;
171 // Trim any quotes.
Alex Deymo020600d2014-11-05 21:05:55 -0800172 base::TrimString(kv_pair.second, "\"", &output);
Chris Sosac1972482013-04-30 22:31:10 -0700173 return output;
174 }
175 }
176 }
177 LOG(ERROR) << "Unable to parse fwid from ec info.";
178 return "";
179}
180
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800181bool WriteFile(const char* path, const void* data, int data_len) {
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800182 DirectFileWriter writer;
183 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
184 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -0700185 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800186 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -0800187 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800188 return true;
189}
190
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700191bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700192 const char* c_buf = static_cast<const char*>(buf);
193 ssize_t bytes_written = 0;
194 while (bytes_written < static_cast<ssize_t>(count)) {
195 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
196 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
197 bytes_written += rc;
198 }
199 return true;
200}
201
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700202bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
203 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700204 size_t bytes_written = 0;
205 int num_attempts = 0;
206 while (bytes_written < count) {
207 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700208 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
209 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700210 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
211 if (rc < 0) {
212 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
213 << " bytes_written=" << bytes_written
214 << " count=" << count << " offset=" << offset;
215 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700216 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
217 bytes_written += rc;
218 }
219 return true;
220}
221
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800222bool WriteAll(FileDescriptorPtr fd, const void* buf, size_t count) {
223 const char* c_buf = static_cast<const char*>(buf);
224 ssize_t bytes_written = 0;
225 while (bytes_written < static_cast<ssize_t>(count)) {
226 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
227 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
228 bytes_written += rc;
229 }
230 return true;
231}
232
233bool PWriteAll(FileDescriptorPtr fd,
234 const void* buf,
235 size_t count,
236 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700237 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
238 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800239 return WriteAll(fd, buf, count);
240}
241
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700242bool PReadAll(int fd, void* buf, size_t count, off_t offset,
243 ssize_t* out_bytes_read) {
244 char* c_buf = static_cast<char*>(buf);
245 ssize_t bytes_read = 0;
246 while (bytes_read < static_cast<ssize_t>(count)) {
247 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
248 offset + bytes_read);
249 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
250 if (rc == 0) {
251 break;
252 }
253 bytes_read += rc;
254 }
255 *out_bytes_read = bytes_read;
256 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700257}
258
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800259bool PReadAll(FileDescriptorPtr fd, void* buf, size_t count, off_t offset,
260 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700261 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
262 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800263 char* c_buf = static_cast<char*>(buf);
264 ssize_t bytes_read = 0;
265 while (bytes_read < static_cast<ssize_t>(count)) {
266 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
267 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
268 if (rc == 0) {
269 break;
270 }
271 bytes_read += rc;
272 }
273 *out_bytes_read = bytes_read;
274 return true;
275}
276
Gilad Arnold19a45f02012-07-19 12:36:10 -0700277// Append |nbytes| of content from |buf| to the vector pointed to by either
278// |vec_p| or |str_p|.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800279static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700280 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700281 CHECK(buf);
282 CHECK(vec_p);
283 vec_p->insert(vec_p->end(), buf, buf + nbytes);
284}
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800285static void AppendBytes(const uint8_t* buf, size_t nbytes,
Alex Deymof329b932014-10-30 01:37:48 -0700286 string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700287 CHECK(buf);
288 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800289 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700290}
291
292// Reads from an open file |fp|, appending the read content to the container
293// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200294// file's content, false otherwise. If |size| is not -1, reads up to |size|
295// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700296template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200297static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700298 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200299 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800300 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200301 while (size == -1 || size > 0) {
302 off_t bytes_to_read = sizeof(buf);
303 if (size > 0 && bytes_to_read > size) {
304 bytes_to_read = size;
305 }
306 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
307 if (!nbytes) {
308 break;
309 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700310 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200311 if (size != -1) {
312 CHECK(size >= static_cast<off_t>(nbytes));
313 size -= nbytes;
314 }
315 }
316 if (ferror(fp)) {
317 return false;
318 }
319 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700320}
321
Darin Petkov8e447e02013-04-16 16:23:50 +0200322// Opens a file |path| for reading and appends its the contents to a container
323// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
324// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700325template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700326static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200327 off_t offset,
328 off_t size,
329 T* out_p) {
330 CHECK_GE(offset, 0);
331 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700332 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200333 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000334 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200335 if (offset) {
336 // Return success without appending any data if a chunk beyond the end of
337 // the file is requested.
338 if (offset >= FileSize(path)) {
339 return true;
340 }
341 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
342 }
343 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000344}
345
Alex Deymo10875d92014-11-10 21:52:57 -0800346// TODO(deymo): This is only used in unittest, but requires the private
347// Read<string>() defined here. Expose Read<string>() or move to base/ version.
348bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700349 FILE* fp = popen(cmd.c_str(), "r");
350 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000351 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200352 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700353 return (success && pclose(fp) >= 0);
354}
355
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700356bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200357 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700358}
359
Darin Petkov8e447e02013-04-16 16:23:50 +0200360bool ReadFile(const string& path, string* out_p) {
361 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700362}
363
Darin Petkov8e447e02013-04-16 16:23:50 +0200364bool ReadFileChunk(const string& path, off_t offset, off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700365 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200366 return ReadFileChunkAndAppend(path, offset, size, out_p);
367}
368
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700369off_t BlockDevSize(int fd) {
370 uint64_t dev_size;
371 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
372 if (rc == -1) {
373 dev_size = -1;
374 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
375 }
376 return dev_size;
377}
378
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700379off_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 -0700430bool SplitPartitionName(const string& partition_name,
431 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800432 int* out_partition_num) {
Alex Vakulenko0103c362016-01-20 07:56:15 -0800433 if (!base::StartsWith(partition_name, "/dev/",
434 base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800435 LOG(ERROR) << "Invalid partition device name: " << partition_name;
436 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700437 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800438
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700439 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
440 if (last_nondigit_pos == string::npos ||
441 (last_nondigit_pos + 1) == partition_name.size()) {
442 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800443 return false;
444 }
445
Alex Deymof329b932014-10-30 01:37:48 -0700446 size_t partition_name_len = string::npos;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700447 if (partition_name[last_nondigit_pos] == '_') {
448 // NAND block devices have weird naming which could be something
449 // like "/dev/ubiblock2_0". We discard "_0" in such a case.
450 size_t prev_nondigit_pos =
451 partition_name.find_last_not_of("0123456789", last_nondigit_pos - 1);
452 if (prev_nondigit_pos == string::npos ||
453 (prev_nondigit_pos + 1) == last_nondigit_pos) {
454 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
455 return false;
456 }
457
458 partition_name_len = last_nondigit_pos - prev_nondigit_pos;
459 last_nondigit_pos = prev_nondigit_pos;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800460 }
461
462 if (out_disk_name) {
463 // Special case for MMC devices which have the following naming scheme:
464 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700465 size_t disk_name_len = last_nondigit_pos;
466 if (partition_name[last_nondigit_pos] != 'p' ||
467 last_nondigit_pos == 0 ||
468 !isdigit(partition_name[last_nondigit_pos - 1])) {
469 disk_name_len++;
470 }
471 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800472 }
473
474 if (out_partition_num) {
Alex Deymof329b932014-10-30 01:37:48 -0700475 string partition_str = partition_name.substr(last_nondigit_pos + 1,
476 partition_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800477 *out_partition_num = atoi(partition_str.c_str());
478 }
479 return true;
480}
481
Alex Deymof329b932014-10-30 01:37:48 -0700482string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800483 if (partition_num < 1) {
484 LOG(ERROR) << "Invalid partition number: " << partition_num;
485 return string();
486 }
487
Alex Vakulenko0103c362016-01-20 07:56:15 -0800488 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800489 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700490 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800491 }
492
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800493 if (IsMtdDeviceName(disk_name)) {
494 // Special case for UBI block devices.
495 // 1. ubiblock is not writable, we need to use plain "ubi".
496 // 2. There is a "_0" suffix.
497 return MakeNandPartitionName(partition_num);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800498 }
499
Alex Deymof329b932014-10-30 01:37:48 -0700500 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700501 if (isdigit(partition_name.back())) {
502 // Special case for devices with names ending with a digit.
503 // Add "p" to separate the disk name from partition number,
504 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800505 partition_name += 'p';
506 }
507
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700508 partition_name += std::to_string(partition_num);
509
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800510 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700511}
512
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800513string MakePartitionNameForMount(const string& part_name) {
514 if (IsMtdDeviceName(part_name)) {
515 int partition_num;
516 if (!SplitPartitionName(part_name, nullptr, &partition_num)) {
517 return "";
518 }
519 return MakeNandPartitionNameForMount(partition_num);
520 }
521 return part_name;
522}
523
Alex Deymof329b932014-10-30 01:37:48 -0700524string ErrnoNumberAsString(int err) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000525 char buf[100];
526 buf[0] = '\0';
527 return strerror_r(err, buf, sizeof(buf));
528}
529
adlr@google.com3defe6a2009-12-04 20:57:17 +0000530bool FileExists(const char* path) {
531 struct stat stbuf;
532 return 0 == lstat(path, &stbuf);
533}
534
Darin Petkov30291ed2010-11-12 10:23:06 -0800535bool IsSymlink(const char* path) {
536 struct stat stbuf;
537 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
538}
539
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800540bool TryAttachingUbiVolume(int volume_num, int timeout) {
541 const string volume_path = base::StringPrintf("/dev/ubi%d_0", volume_num);
542 if (FileExists(volume_path.c_str())) {
543 return true;
544 }
545
546 int exit_code;
547 vector<string> cmd = {
548 "ubiattach",
549 "-m",
550 base::StringPrintf("%d", volume_num),
551 "-d",
552 base::StringPrintf("%d", volume_num)
553 };
554 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
555 TEST_AND_RETURN_FALSE(exit_code == 0);
556
557 cmd = {
558 "ubiblock",
559 "--create",
560 volume_path
561 };
562 TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &exit_code, nullptr));
563 TEST_AND_RETURN_FALSE(exit_code == 0);
564
565 while (timeout > 0 && !FileExists(volume_path.c_str())) {
566 sleep(1);
567 timeout--;
568 }
569
570 return FileExists(volume_path.c_str());
571}
572
Alex Deymof329b932014-10-30 01:37:48 -0700573bool MakeTempFile(const string& base_filename_template,
574 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700575 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700576 base::FilePath filename_template;
577 TEST_AND_RETURN_FALSE(
578 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700579 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700580 vector<char> buf(filename_template.value().size() + 1);
581 memcpy(buf.data(), filename_template.value().data(),
582 filename_template.value().size());
583 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700584
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800585 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700586 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
587 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800588 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700589 }
590 if (fd) {
591 *fd = mkstemp_fd;
592 } else {
593 close(mkstemp_fd);
594 }
595 return true;
596}
597
Alex Deymof329b932014-10-30 01:37:48 -0700598bool MakeTempDirectory(const string& base_dirname_template,
599 string* dirname) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700600 base::FilePath dirname_template;
601 TEST_AND_RETURN_FALSE(GetTempName(base_dirname_template, &dirname_template));
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700602 DCHECK(dirname);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700603 vector<char> buf(dirname_template.value().size() + 1);
604 memcpy(buf.data(), dirname_template.value().data(),
605 dirname_template.value().size());
606 buf[dirname_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700607
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800608 char* return_code = mkdtemp(buf.data());
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700609 TEST_AND_RETURN_FALSE_ERRNO(return_code != nullptr);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800610 *dirname = buf.data();
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700611 return true;
612}
613
adlr@google.com3defe6a2009-12-04 20:57:17 +0000614bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700615 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800616 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800617 const string& type,
618 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800619 vector<const char*> fstypes;
620 if (type.empty()) {
621 fstypes = {"ext2", "ext3", "ext4", "squashfs"};
622 } else {
623 fstypes = {type.c_str()};
624 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800625 for (const char* fstype : fstypes) {
626 int rc = mount(device.c_str(), mountpoint.c_str(), fstype, mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800627 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800628 if (rc == 0)
629 return true;
630
631 PLOG(WARNING) << "Unable to mount destination device " << device
632 << " on " << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000633 }
Alex Deymo390efed2016-02-18 11:00:40 -0800634 if (!type.empty()) {
635 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
636 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800637 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000638}
639
640bool UnmountFilesystem(const string& mountpoint) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700641 for (int num_retries = 0; ; ++num_retries) {
642 if (umount(mountpoint.c_str()) == 0)
643 break;
644
645 TEST_AND_RETURN_FALSE_ERRNO(errno == EBUSY &&
646 num_retries < kUnmountMaxNumOfRetries);
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700647 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700648 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000649 return true;
650}
651
Alex Deymof329b932014-10-30 01:37:48 -0700652bool GetFilesystemSize(const string& device,
Darin Petkovd3f8c892010-10-12 21:38:45 -0700653 int* out_block_count,
654 int* out_block_size) {
655 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
Alex Deymoe7141c62014-10-17 14:03:01 -0700656 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700657 ScopedFdCloser fd_closer(&fd);
658 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
659}
660
661bool GetFilesystemSizeFromFD(int fd,
662 int* out_block_count,
663 int* out_block_size) {
664 TEST_AND_RETURN_FALSE(fd >= 0);
665
Alex Deymo192393b2014-11-10 15:58:38 -0800666 // Determine the filesystem size by directly reading the block count and
667 // block size information from the superblock. Supported FS are ext3 and
668 // squashfs.
669
670 // Read from the fd only once and detect in memory. The first 2 KiB is enough
671 // to read the ext2 superblock (located at offset 1024) and the squashfs
672 // superblock (located at offset 0).
673 const ssize_t kBufferSize = 2048;
674
675 uint8_t buffer[kBufferSize];
676 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, 0)) != kBufferSize) {
677 PLOG(ERROR) << "Unable to read the file system header:";
Darin Petkovd3f8c892010-10-12 21:38:45 -0700678 return false;
679 }
Alex Deymo192393b2014-11-10 15:58:38 -0800680
681 if (GetSquashfs4Size(buffer, kBufferSize, out_block_count, out_block_size))
682 return true;
683 if (GetExt3Size(buffer, kBufferSize, out_block_count, out_block_size))
684 return true;
685
686 LOG(ERROR) << "Unable to determine file system type.";
687 return false;
688}
689
690bool GetExt3Size(const uint8_t* buffer, size_t buffer_size,
691 int* out_block_count,
692 int* out_block_size) {
693 // See include/linux/ext2_fs.h for more details on the structure. We obtain
694 // ext2 constants from ext2fs/ext2fs.h header but we don't link with the
695 // library.
696 if (buffer_size < SUPERBLOCK_OFFSET + SUPERBLOCK_SIZE)
697 return false;
698
699 const uint8_t* superblock = buffer + SUPERBLOCK_OFFSET;
700
701 // ext3_fs.h: ext3_super_block.s_blocks_count
702 uint32_t block_count =
703 *reinterpret_cast<const uint32_t*>(superblock + 1 * sizeof(int32_t));
704
705 // ext3_fs.h: ext3_super_block.s_log_block_size
706 uint32_t log_block_size =
707 *reinterpret_cast<const uint32_t*>(superblock + 6 * sizeof(int32_t));
708
709 // ext3_fs.h: ext3_super_block.s_magic
710 uint16_t magic =
711 *reinterpret_cast<const uint16_t*>(superblock + 14 * sizeof(int32_t));
712
Darin Petkovd3f8c892010-10-12 21:38:45 -0700713 block_count = le32toh(block_count);
Alex Deymo192393b2014-11-10 15:58:38 -0800714 log_block_size = le32toh(log_block_size) + EXT2_MIN_BLOCK_LOG_SIZE;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700715 magic = le16toh(magic);
716
717 // Sanity check the parameters.
Alex Deymo192393b2014-11-10 15:58:38 -0800718 TEST_AND_RETURN_FALSE(magic == EXT2_SUPER_MAGIC);
719 TEST_AND_RETURN_FALSE(log_block_size >= EXT2_MIN_BLOCK_LOG_SIZE &&
720 log_block_size <= EXT2_MAX_BLOCK_LOG_SIZE);
Darin Petkovd3f8c892010-10-12 21:38:45 -0700721 TEST_AND_RETURN_FALSE(block_count > 0);
722
Alex Deymo192393b2014-11-10 15:58:38 -0800723 if (out_block_count)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700724 *out_block_count = block_count;
Alex Deymo192393b2014-11-10 15:58:38 -0800725 if (out_block_size)
726 *out_block_size = 1 << log_block_size;
727 return true;
728}
729
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800730bool GetSquashfs4Size(const uint8_t* buffer, size_t buffer_size,
Alex Deymo192393b2014-11-10 15:58:38 -0800731 int* out_block_count,
732 int* out_block_size) {
733 // See fs/squashfs/squashfs_fs.h for format details. We only support
734 // Squashfs 4.x little endian.
735
736 // sizeof(struct squashfs_super_block)
737 const size_t kSquashfsSuperBlockSize = 96;
738 if (buffer_size < kSquashfsSuperBlockSize)
739 return false;
740
741 // Check magic, squashfs_fs.h: SQUASHFS_MAGIC
742 if (memcmp(buffer, "hsqs", 4) != 0)
743 return false; // Only little endian is supported.
744
745 // squashfs_fs.h: struct squashfs_super_block.s_major
746 uint16_t s_major = *reinterpret_cast<const uint16_t*>(
747 buffer + 5 * sizeof(uint32_t) + 4 * sizeof(uint16_t));
748
749 if (s_major != 4) {
750 LOG(ERROR) << "Found unsupported squashfs major version " << s_major;
751 return false;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700752 }
Alex Deymo192393b2014-11-10 15:58:38 -0800753
754 // squashfs_fs.h: struct squashfs_super_block.bytes_used
755 uint64_t bytes_used = *reinterpret_cast<const int64_t*>(
756 buffer + 5 * sizeof(uint32_t) + 6 * sizeof(uint16_t) + sizeof(uint64_t));
757
758 const int block_size = 4096;
759
760 // The squashfs' bytes_used doesn't need to be aligned with the block boundary
761 // so we round up to the nearest blocksize.
762 if (out_block_count)
763 *out_block_count = (bytes_used + block_size - 1) / block_size;
764 if (out_block_size)
Darin Petkovd3f8c892010-10-12 21:38:45 -0700765 *out_block_size = block_size;
Darin Petkovd3f8c892010-10-12 21:38:45 -0700766 return true;
767}
768
Alex Deymo60ca1a72015-06-18 18:19:15 -0700769bool IsExtFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700770 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700771 // The first 2 KiB is enough to read the ext2 superblock (located at offset
772 // 1024).
773 if (!ReadFileChunk(device, 0, 2048, &header))
774 return false;
775 return GetExt3Size(header.data(), header.size(), nullptr, nullptr);
776}
777
Alex Deymo60ca1a72015-06-18 18:19:15 -0700778bool IsSquashfsFilesystem(const string& device) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700779 brillo::Blob header;
Alex Deymode942f32015-03-13 11:57:15 -0700780 // The first 96 is enough to read the squashfs superblock.
781 const ssize_t kSquashfsSuperBlockSize = 96;
782 if (!ReadFileChunk(device, 0, kSquashfsSuperBlockSize, &header))
783 return false;
784 return GetSquashfs4Size(header.data(), header.size(), nullptr, nullptr);
785}
786
Alex Deymo032e7722014-03-25 17:53:56 -0700787// Tries to parse the header of an ELF file to obtain a human-readable
788// description of it on the |output| string.
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800789static bool GetFileFormatELF(const uint8_t* buffer, size_t size,
790 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700791 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700792 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700793 return false;
794 *output = "ELF";
795
796 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700797 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700798 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700799 switch (buffer[EI_CLASS]) {
800 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700801 *output += " 32-bit";
802 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700803 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700804 *output += " 64-bit";
805 break;
806 default:
807 *output += " ?-bit";
808 }
809
810 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700811 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700812 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800813 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700814 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700815 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700816 *output += " little-endian";
817 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700818 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700819 *output += " big-endian";
820 break;
821 default:
822 *output += " ?-endian";
823 // Don't parse anything after the 0x10 offset if endianness is unknown.
824 return true;
825 }
826
Alex Deymoc1711e22014-08-08 13:16:23 -0700827 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
828 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
829 // and size is the same for both 32 and 64 bits.
830 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700831 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700832 uint16_t e_machine;
Alex Deymo032e7722014-03-25 17:53:56 -0700833 // Fix endianess regardless of the host endianess.
Alex Deymoc1711e22014-08-08 13:16:23 -0700834 if (ei_data == ELFDATA2LSB)
835 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700836 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700837 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700838
839 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700840 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700841 *output += " x86";
842 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700843 case EM_MIPS:
844 *output += " mips";
845 break;
846 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700847 *output += " arm";
848 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700849 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700850 *output += " x86-64";
851 break;
852 default:
853 *output += " unknown-arch";
854 }
855 return true;
856}
857
858string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700859 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700860 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
861 return "File not found.";
862
863 string result;
864 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
865 return result;
866
867 return "data";
868}
869
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800870namespace {
871// Do the actual trigger. We do it as a main-loop callback to (try to) get a
872// consistent stack trace.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700873void TriggerCrashReporterUpload() {
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800874 pid_t pid = fork();
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700875 CHECK_GE(pid, 0) << "fork failed"; // fork() failed. Something is very wrong.
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800876 if (pid == 0) {
877 // We are the child. Crash.
878 abort(); // never returns
879 }
880 // We are the parent. Wait for child to terminate.
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700881 pid_t result = waitpid(pid, nullptr, 0);
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800882 LOG_IF(ERROR, result < 0) << "waitpid() failed";
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800883}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700884} // namespace
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800885
886void ScheduleCrashReporterUpload() {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700887 brillo::MessageLoop::current()->PostTask(
Alex Deymo60ca1a72015-06-18 18:19:15 -0700888 FROM_HERE,
889 base::Bind(&TriggerCrashReporterUpload));
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800890}
891
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700892int FuzzInt(int value, unsigned int range) {
893 int min = value - range / 2;
894 int max = value + range - range / 2;
895 return base::RandInt(min, max);
896}
897
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700898string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800899 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700900}
901
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800902string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400903 string str;
904
905 // Handle negative durations by prefixing with a minus.
906 if (delta.ToInternalValue() < 0) {
907 delta *= -1;
908 str = "-";
909 }
910
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700911 // Canonicalize into days, hours, minutes, seconds and microseconds.
912 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800913 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700914 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800915 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700916 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800917 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700918 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800919 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700920 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800921
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700922 if (days)
923 base::StringAppendF(&str, "%ud", days);
924 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800925 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700926 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800927 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700928 base::StringAppendF(&str, "%u", secs);
929 if (usecs) {
930 int width = 6;
931 while ((usecs / 10) * 10 == usecs) {
932 usecs /= 10;
933 width--;
934 }
935 base::StringAppendF(&str, ".%0*u", width, usecs);
936 }
937 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800938 return str;
939}
940
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700941string ToString(const Time utc_time) {
942 Time::Exploded exp_time;
943 utc_time.UTCExplode(&exp_time);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700944 return base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700945 exp_time.month,
946 exp_time.day_of_month,
947 exp_time.year,
948 exp_time.hour,
949 exp_time.minute,
950 exp_time.second);
951}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000952
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700953string ToString(bool b) {
954 return (b ? "true" : "false");
955}
956
Alex Deymo1c656c42013-06-28 11:02:14 -0700957string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700958 switch (source) {
959 case kDownloadSourceHttpsServer: return "HttpsServer";
960 case kDownloadSourceHttpServer: return "HttpServer";
David Zeuthenbb8bdc72013-09-03 13:43:48 -0700961 case kDownloadSourceHttpPeer: return "HttpPeer";
Jay Srinivasan19409b72013-04-12 19:23:36 -0700962 case kNumDownloadSources: return "Unknown";
963 // Don't add a default case to let the compiler warn about newly added
964 // download sources which should be added here.
965 }
966
967 return "Unknown";
968}
969
Alex Deymo1c656c42013-06-28 11:02:14 -0700970string ToString(PayloadType payload_type) {
971 switch (payload_type) {
972 case kPayloadTypeDelta: return "Delta";
973 case kPayloadTypeFull: return "Full";
974 case kPayloadTypeForcedFull: return "ForcedFull";
975 case kNumPayloadTypes: return "Unknown";
976 // Don't add a default case to let the compiler warn about newly added
977 // payload types which should be added here.
978 }
979
980 return "Unknown";
981}
982
David Zeuthena99981f2013-04-29 13:42:47 -0700983ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700984 // Ignore the higher order bits in the code by applying the mask as
985 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700986 // with values less than ErrorCode::kUmaReportedMax.
987 ErrorCode base_code = static_cast<ErrorCode>(
988 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700989
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800990 // Make additional adjustments required for UMA and error classification.
991 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
992 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700993 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700994 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800995 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800996 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700997 << " to ErrorCode::kOmahaErrorInHTTPResponse";
998 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700999 }
1000
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001001 return base_code;
1002}
1003
Gilad Arnold30dedd82013-07-03 06:19:09 -07001004bool CreatePowerwashMarkerFile(const char* file_path) {
1005 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
1006 bool result = utils::WriteFile(marker_file,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001007 kPowerwashCommand,
1008 strlen(kPowerwashCommand));
Gilad Arnold30dedd82013-07-03 06:19:09 -07001009 if (result) {
1010 LOG(INFO) << "Created " << marker_file << " to powerwash on next reboot";
1011 } else {
1012 PLOG(ERROR) << "Error in creating powerwash marker file: " << marker_file;
1013 }
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001014
1015 return result;
1016}
1017
Gilad Arnold30dedd82013-07-03 06:19:09 -07001018bool DeletePowerwashMarkerFile(const char* file_path) {
1019 const char* marker_file = file_path ? file_path : kPowerwashMarkerFile;
Alex Vakulenko75039d72014-03-25 12:36:28 -07001020 const base::FilePath kPowerwashMarkerPath(marker_file);
1021 bool result = base::DeleteFile(kPowerwashMarkerPath, false);
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001022
1023 if (result)
1024 LOG(INFO) << "Successfully deleted the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001025 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001026 else
1027 PLOG(ERROR) << "Could not delete the powerwash marker file : "
Gilad Arnold30dedd82013-07-03 06:19:09 -07001028 << marker_file;
Jay Srinivasan1c0fe792013-03-28 16:45:25 -07001029
1030 return result;
1031}
1032
David Zeuthen27a48bc2013-08-06 12:06:29 -07001033Time TimeFromStructTimespec(struct timespec *ts) {
Ben Chan9abb7632014-08-07 00:10:53 -07001034 int64_t us = static_cast<int64_t>(ts->tv_sec) * Time::kMicrosecondsPerSecond +
1035 static_cast<int64_t>(ts->tv_nsec) / Time::kNanosecondsPerMicrosecond;
David Zeuthen27a48bc2013-08-06 12:06:29 -07001036 return Time::UnixEpoch() + TimeDelta::FromMicroseconds(us);
1037}
1038
Alex Deymof329b932014-10-30 01:37:48 -07001039string StringVectorToString(const vector<string> &vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -07001040 string str = "[";
Alex Deymof329b932014-10-30 01:37:48 -07001041 for (vector<string>::const_iterator i = vec_str.begin();
1042 i != vec_str.end(); ++i) {
1043 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -07001044 str += ", ";
1045 str += '"';
1046 str += *i;
1047 str += '"';
1048 }
1049 str += "]";
1050 return str;
1051}
1052
David Zeuthen8f191b22013-08-06 12:27:50 -07001053string CalculateP2PFileId(const string& payload_hash, size_t payload_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001054 string encoded_hash = brillo::data_encoding::Base64Encode(payload_hash);
Alex Deymoc00c98a2015-03-17 17:38:00 -07001055 return base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001056 payload_size,
1057 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001058}
1059
Alex Deymof329b932014-10-30 01:37:48 -07001060bool DecodeAndStoreBase64String(const string& base64_encoded,
David Zeuthene7f89172013-10-31 10:21:04 -07001061 base::FilePath *out_path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001062 brillo::Blob contents;
David Zeuthene7f89172013-10-31 10:21:04 -07001063
1064 out_path->clear();
1065
1066 if (base64_encoded.size() == 0) {
1067 LOG(ERROR) << "Can't decode empty string.";
1068 return false;
1069 }
1070
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001071 if (!brillo::data_encoding::Base64Decode(base64_encoded, &contents) ||
David Zeuthene7f89172013-10-31 10:21:04 -07001072 contents.size() == 0) {
1073 LOG(ERROR) << "Error decoding base64.";
1074 return false;
1075 }
1076
Alex Vakulenko75039d72014-03-25 12:36:28 -07001077 FILE *file = base::CreateAndOpenTemporaryFile(out_path);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001078 if (file == nullptr) {
David Zeuthene7f89172013-10-31 10:21:04 -07001079 LOG(ERROR) << "Error creating temporary file.";
1080 return false;
1081 }
1082
Alex Vakulenko981a9fb2015-02-09 12:51:24 -08001083 if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
David Zeuthene7f89172013-10-31 10:21:04 -07001084 PLOG(ERROR) << "Error writing to temporary file.";
1085 if (fclose(file) != 0)
1086 PLOG(ERROR) << "Error closing temporary file.";
1087 if (unlink(out_path->value().c_str()) != 0)
1088 PLOG(ERROR) << "Error unlinking temporary file.";
1089 out_path->clear();
1090 return false;
1091 }
1092
1093 if (fclose(file) != 0) {
1094 PLOG(ERROR) << "Error closing temporary file.";
1095 out_path->clear();
1096 return false;
1097 }
1098
1099 return true;
1100}
1101
Alex Deymof329b932014-10-30 01:37:48 -07001102bool ConvertToOmahaInstallDate(Time time, int *out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001103 time_t unix_time = time.ToTimeT();
1104 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1105 const time_t kOmahaEpoch = 1167638400;
1106 const int64_t kNumSecondsPerWeek = 7*24*3600;
1107 const int64_t kNumDaysPerWeek = 7;
1108
1109 time_t omaha_time = unix_time - kOmahaEpoch;
1110
1111 if (omaha_time < 0)
1112 return false;
1113
1114 // Note, as per the comment in utils.h we are deliberately not
1115 // handling DST correctly.
1116
1117 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1118 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1119
1120 return true;
1121}
1122
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001123bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -07001124 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001125 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001126 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001127 if (!base::StringToUint(result, minor_version)) {
1128 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1129 return false;
1130 }
Allie Wood78750a42015-02-11 15:42:11 -08001131 return true;
1132 }
1133 return false;
1134}
1135
Alex Deymo60ca1a72015-06-18 18:19:15 -07001136bool ReadExtents(const string& path, const vector<Extent>& extents,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001137 brillo::Blob* out_data, ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001138 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001139 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001140 ssize_t bytes_read = 0;
1141 int fd = open(path.c_str(), O_RDONLY);
1142 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
1143 ScopedFdCloser fd_closer(&fd);
1144
Gilad Arnold41e34742015-05-11 11:31:50 -07001145 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001146 ssize_t bytes_read_this_iteration = 0;
1147 ssize_t bytes = extent.num_blocks() * block_size;
1148 TEST_AND_RETURN_FALSE(bytes_read + bytes <= out_data_size);
1149 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1150 &data[bytes_read],
1151 bytes,
1152 extent.start_block() * block_size,
1153 &bytes_read_this_iteration));
1154 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1155 bytes_read += bytes_read_this_iteration;
1156 }
1157 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1158 *out_data = data;
1159 return true;
1160}
1161
Alex Deymodd132f32015-09-14 19:12:07 -07001162bool GetBootId(string* boot_id) {
1163 TEST_AND_RETURN_FALSE(
1164 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1165 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1166 return true;
1167}
1168
adlr@google.com3defe6a2009-12-04 20:57:17 +00001169} // namespace utils
1170
1171} // namespace chromeos_update_engine