blob: 9cb8053c9b6f6c183d1de139b7b0ed2464bf5935 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
adlr@google.com3defe6a2009-12-04 20:57:17 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -07006
adlr@google.com3defe6a2009-12-04 20:57:17 +00007#include <sys/mount.h>
Darin Petkovc6c135c2010-08-11 13:36:18 -07008#include <sys/resource.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +00009#include <sys/stat.h>
10#include <sys/types.h>
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -080011#include <sys/wait.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000012#include <dirent.h>
13#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080014#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000015#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070019
adlr@google.com3defe6a2009-12-04 20:57:17 +000020#include <algorithm>
Darin Petkovf74eb652010-08-04 12:08:38 -070021
Darin Petkovd3f8c892010-10-12 21:38:45 -070022#include <base/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050023#include <base/file_path.h>
24#include <base/file_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040025#include <base/logging.h>
Will Drewry8f71da82010-08-30 14:07:11 -050026#include <base/rand_util.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070027#include <base/string_number_conversions.h>
Will Drewry8f71da82010-08-30 14:07:11 -050028#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040029#include <base/stringprintf.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080030#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050031#include <rootdev/rootdev.h>
32
Andrew de los Reyes970bb282009-12-09 16:34:04 -080033#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070034#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070035#include "update_engine/subprocess.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000036
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070037using base::Time;
adlr@google.com3defe6a2009-12-04 20:57:17 +000038using std::min;
39using std::string;
40using std::vector;
41
42namespace chromeos_update_engine {
43
44namespace utils {
45
Darin Petkova07586b2010-10-20 13:41:15 -070046static const char kDevImageMarker[] = "/root/.dev_mode";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070047const char* const kStatefulPartition = "/mnt/stateful_partition";
Darin Petkov2a0e6332010-09-24 14:43:41 -070048
Darin Petkov33d30642010-08-04 10:18:57 -070049bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070050 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070051}
52
Darin Petkovc91dd6b2011-01-10 12:31:34 -080053bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070054 // TODO(petkov): Convert to a library call once a crossystem library is
55 // available (crosbug.com/13291).
56 int exit_code = 0;
57 vector<string> cmd(1, "/usr/bin/crossystem");
58 cmd.push_back("devsw_boot?1");
59
60 // Assume dev mode if the dev switch is set to 1 and there was no error
61 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070062 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070063 bool dev_mode = success && exit_code == 0;
64 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
65 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080066}
67
Darin Petkovf2065b42011-05-17 16:36:27 -070068string GetHardwareClass() {
69 // TODO(petkov): Convert to a library call once a crossystem library is
70 // available (crosbug.com/13291).
71 int exit_code = 0;
72 vector<string> cmd(1, "/usr/bin/crossystem");
73 cmd.push_back("hwid");
74
75 string hwid;
76 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
77 if (success && !exit_code) {
78 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
79 return hwid;
80 }
81 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
82 return "";
83}
84
Andrew de los Reyes970bb282009-12-09 16:34:04 -080085bool WriteFile(const char* path, const char* data, int data_len) {
86 DirectFileWriter writer;
87 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
88 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -070089 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -080090 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -080091 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -080092 return true;
93}
94
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070095bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070096 const char* c_buf = static_cast<const char*>(buf);
97 ssize_t bytes_written = 0;
98 while (bytes_written < static_cast<ssize_t>(count)) {
99 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
100 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
101 bytes_written += rc;
102 }
103 return true;
104}
105
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700106bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
107 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700108 size_t bytes_written = 0;
109 int num_attempts = 0;
110 while (bytes_written < count) {
111 num_attempts++;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700112 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
113 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700114 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
115 if (rc < 0) {
116 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
117 << " bytes_written=" << bytes_written
118 << " count=" << count << " offset=" << offset;
119 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700120 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
121 bytes_written += rc;
122 }
123 return true;
124}
125
126bool PReadAll(int fd, void* buf, size_t count, off_t offset,
127 ssize_t* out_bytes_read) {
128 char* c_buf = static_cast<char*>(buf);
129 ssize_t bytes_read = 0;
130 while (bytes_read < static_cast<ssize_t>(count)) {
131 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
132 offset + bytes_read);
133 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
134 if (rc == 0) {
135 break;
136 }
137 bytes_read += rc;
138 }
139 *out_bytes_read = bytes_read;
140 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700141
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700142}
143
adlr@google.com3defe6a2009-12-04 20:57:17 +0000144bool ReadFile(const std::string& path, std::vector<char>* out) {
145 CHECK(out);
146 FILE* fp = fopen(path.c_str(), "r");
147 if (!fp)
148 return false;
149 const size_t kChunkSize = 1024;
150 size_t read_size;
151 do {
152 char buf[kChunkSize];
153 read_size = fread(buf, 1, kChunkSize, fp);
154 if (read_size == 0)
155 break;
156 out->insert(out->end(), buf, buf + read_size);
157 } while (read_size == kChunkSize);
158 bool success = !ferror(fp);
159 TEST_AND_RETURN_FALSE_ERRNO(fclose(fp) == 0);
160 return success;
161}
162
163bool ReadFileToString(const std::string& path, std::string* out) {
164 vector<char> data;
165 bool success = ReadFile(path, &data);
166 if (!success) {
167 return false;
168 }
169 (*out) = string(&data[0], data.size());
170 return true;
171}
172
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700173off_t FileSize(const string& path) {
174 struct stat stbuf;
175 int rc = stat(path.c_str(), &stbuf);
176 CHECK_EQ(rc, 0);
177 if (rc < 0)
178 return rc;
179 return stbuf.st_size;
180}
181
adlr@google.com3defe6a2009-12-04 20:57:17 +0000182void HexDumpArray(const unsigned char* const arr, const size_t length) {
183 const unsigned char* const char_arr =
184 reinterpret_cast<const unsigned char* const>(arr);
185 LOG(INFO) << "Logging array of length: " << length;
186 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700187 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000188 const unsigned int bytes_remaining = length - i;
189 const unsigned int bytes_per_this_line = min(bytes_per_line,
190 bytes_remaining);
191 char header[100];
192 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
193 TEST_AND_RETURN(r == 13);
194 string line = header;
195 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
196 char buf[20];
197 unsigned char c = char_arr[i + j];
198 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
199 TEST_AND_RETURN(r == 3);
200 line += buf;
201 }
202 LOG(INFO) << line;
203 }
204}
205
206namespace {
207class ScopedDirCloser {
208 public:
209 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
210 ~ScopedDirCloser() {
211 if (dir_ && *dir_) {
212 int r = closedir(*dir_);
213 TEST_AND_RETURN_ERRNO(r == 0);
214 *dir_ = NULL;
215 dir_ = NULL;
216 }
217 }
218 private:
219 DIR** dir_;
220};
221} // namespace {}
222
223bool RecursiveUnlinkDir(const std::string& path) {
224 struct stat stbuf;
225 int r = lstat(path.c_str(), &stbuf);
226 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
227 if ((r < 0) && (errno == ENOENT))
228 // path request is missing. that's fine.
229 return true;
230 if (!S_ISDIR(stbuf.st_mode)) {
231 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700232 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000233 // success or path disappeared before we could unlink.
234 return true;
235 }
236 {
237 // We have a dir, unlink all children, then delete dir
238 DIR *dir = opendir(path.c_str());
239 TEST_AND_RETURN_FALSE_ERRNO(dir);
240 ScopedDirCloser dir_closer(&dir);
241 struct dirent dir_entry;
242 struct dirent *dir_entry_p;
243 int err = 0;
244 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
245 if (dir_entry_p == NULL) {
246 // end of stream reached
247 break;
248 }
249 // Skip . and ..
250 if (!strcmp(dir_entry_p->d_name, ".") ||
251 !strcmp(dir_entry_p->d_name, ".."))
252 continue;
253 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700254 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000255 }
256 TEST_AND_RETURN_FALSE(err == 0);
257 }
258 // unlink dir
259 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
260 return true;
261}
262
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700263string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700264 FilePath device_path(partition_device);
265 if (device_path.DirName().value() != "/dev") {
266 return "";
267 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700268 string::const_iterator it = --partition_device.end();
269 for (; it >= partition_device.begin(); --it) {
270 if (!isdigit(*it))
271 break;
272 }
273 // Some devices contain a p before the partitions. For example:
274 // /dev/mmc0p4 should be shortened to /dev/mmc0.
275 if (*it == 'p')
276 --it;
277 return string(partition_device.begin(), it + 1);
278}
279
280string PartitionNumber(const string& partition_device) {
281 CHECK(!partition_device.empty());
282 string::const_iterator it = --partition_device.end();
283 for (; it >= partition_device.begin(); --it) {
284 if (!isdigit(*it))
285 break;
286 }
287 return string(it + 1, partition_device.end());
288}
289
Darin Petkovf74eb652010-08-04 12:08:38 -0700290string SysfsBlockDevice(const string& device) {
291 FilePath device_path(device);
292 if (device_path.DirName().value() != "/dev") {
293 return "";
294 }
295 return FilePath("/sys/block").Append(device_path.BaseName()).value();
296}
297
298bool IsRemovableDevice(const std::string& device) {
299 string sysfs_block = SysfsBlockDevice(device);
300 string removable;
301 if (sysfs_block.empty() ||
302 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
303 &removable)) {
304 return false;
305 }
306 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
307 return removable == "1";
308}
309
adlr@google.com3defe6a2009-12-04 20:57:17 +0000310std::string ErrnoNumberAsString(int err) {
311 char buf[100];
312 buf[0] = '\0';
313 return strerror_r(err, buf, sizeof(buf));
314}
315
316std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
317 string ret;
318 bool last_insert_was_slash = false;
319 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
320 if (*it == '/') {
321 if (last_insert_was_slash)
322 continue;
323 last_insert_was_slash = true;
324 } else {
325 last_insert_was_slash = false;
326 }
327 ret.push_back(*it);
328 }
329 if (strip_trailing_slash && last_insert_was_slash) {
330 string::size_type last_non_slash = ret.find_last_not_of('/');
331 if (last_non_slash != string::npos) {
332 ret.resize(last_non_slash + 1);
333 } else {
334 ret = "";
335 }
336 }
337 return ret;
338}
339
340bool FileExists(const char* path) {
341 struct stat stbuf;
342 return 0 == lstat(path, &stbuf);
343}
344
Darin Petkov30291ed2010-11-12 10:23:06 -0800345bool IsSymlink(const char* path) {
346 struct stat stbuf;
347 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
348}
349
adlr@google.com3defe6a2009-12-04 20:57:17 +0000350std::string TempFilename(string path) {
351 static const string suffix("XXXXXX");
352 CHECK(StringHasSuffix(path, suffix));
353 do {
354 string new_suffix;
355 for (unsigned int i = 0; i < suffix.size(); i++) {
356 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
357 if (r < 26)
358 new_suffix.append(1, 'a' + r);
359 else if (r < (26 * 2))
360 new_suffix.append(1, 'A' + r - 26);
361 else
362 new_suffix.append(1, '0' + r - (26 * 2));
363 }
364 CHECK_EQ(new_suffix.size(), suffix.size());
365 path.resize(path.size() - new_suffix.size());
366 path.append(new_suffix);
367 } while (FileExists(path.c_str()));
368 return path;
369}
370
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700371bool MakeTempFile(const std::string& filename_template,
372 std::string* filename,
373 int* fd) {
374 DCHECK(filename || fd);
375 vector<char> buf(filename_template.size() + 1);
376 memcpy(&buf[0], filename_template.data(), filename_template.size());
377 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700378
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700379 int mkstemp_fd = mkstemp(&buf[0]);
380 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
381 if (filename) {
382 *filename = &buf[0];
383 }
384 if (fd) {
385 *fd = mkstemp_fd;
386 } else {
387 close(mkstemp_fd);
388 }
389 return true;
390}
391
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700392bool MakeTempDirectory(const std::string& dirname_template,
393 std::string* dirname) {
394 DCHECK(dirname);
395 vector<char> buf(dirname_template.size() + 1);
396 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
397 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700398
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700399 char* return_code = mkdtemp(&buf[0]);
400 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
401 *dirname = &buf[0];
402 return true;
403}
404
adlr@google.com3defe6a2009-12-04 20:57:17 +0000405bool StringHasSuffix(const std::string& str, const std::string& suffix) {
406 if (suffix.size() > str.size())
407 return false;
408 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
409}
410
411bool StringHasPrefix(const std::string& str, const std::string& prefix) {
412 if (prefix.size() > str.size())
413 return false;
414 return 0 == str.compare(0, prefix.size(), prefix);
415}
416
Will Drewry8f71da82010-08-30 14:07:11 -0500417const std::string BootDevice() {
418 char boot_path[PATH_MAX];
419 // Resolve the boot device path fully, including dereferencing
420 // through dm-verity.
421 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
422
423 if (ret < 0) {
424 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000425 return "";
426 }
Will Drewry8f71da82010-08-30 14:07:11 -0500427 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
428
429 // This local variable is used to construct the return string and is not
430 // passed around after use.
431 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000432}
433
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700434const string BootKernelDevice(const std::string& boot_device) {
435 // Currntly this assumes the last digit of the boot device is
436 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
437 // get the kernel device.
438 string ret = boot_device;
439 if (ret.empty())
440 return ret;
441 char last_char = ret[ret.size() - 1];
442 if (last_char == '3' || last_char == '5' || last_char == '7') {
443 ret[ret.size() - 1] = last_char - 1;
444 return ret;
445 }
446 return "";
447}
448
adlr@google.com3defe6a2009-12-04 20:57:17 +0000449bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700450 const string& mountpoint,
451 unsigned long mountflags) {
452 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000453 if (rc < 0) {
454 string msg = ErrnoNumberAsString(errno);
455 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
456 << device << " on " << mountpoint;
457 return false;
458 }
459 return true;
460}
461
462bool UnmountFilesystem(const string& mountpoint) {
463 TEST_AND_RETURN_FALSE_ERRNO(umount(mountpoint.c_str()) == 0);
464 return true;
465}
466
Darin Petkovd3f8c892010-10-12 21:38:45 -0700467bool GetFilesystemSize(const std::string& device,
468 int* out_block_count,
469 int* out_block_size) {
470 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
471 TEST_AND_RETURN_FALSE(fd >= 0);
472 ScopedFdCloser fd_closer(&fd);
473 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
474}
475
476bool GetFilesystemSizeFromFD(int fd,
477 int* out_block_count,
478 int* out_block_size) {
479 TEST_AND_RETURN_FALSE(fd >= 0);
480
481 // Determine the ext3 filesystem size by directly reading the block count and
482 // block size information from the superblock. See include/linux/ext3_fs.h for
483 // more details on the structure.
484 ssize_t kBufferSize = 16 * sizeof(uint32_t);
485 char buffer[kBufferSize];
486 const int kSuperblockOffset = 1024;
487 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
488 kBufferSize) {
489 PLOG(ERROR) << "Unable to determine file system size:";
490 return false;
491 }
492 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
493 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
494 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
495 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
496 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
497 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
498 block_count = le32toh(block_count);
499 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
500 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
501 magic = le16toh(magic);
502
503 // Sanity check the parameters.
504 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
505 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
506 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
507 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
508 int block_size = 1 << log_block_size;
509 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
510 block_size <= kExt3MaxBlockSize);
511 TEST_AND_RETURN_FALSE(block_count > 0);
512
513 if (out_block_count) {
514 *out_block_count = block_count;
515 }
516 if (out_block_size) {
517 *out_block_size = block_size;
518 }
519 return true;
520}
521
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700522bool GetBootloader(BootLoader* out_bootloader) {
523 // For now, hardcode to syslinux.
524 *out_bootloader = BootLoader_SYSLINUX;
525 return true;
526}
527
Darin Petkova0b9e772011-10-06 05:05:56 -0700528string GetAndFreeGError(GError** error) {
529 if (!*error) {
530 return "Unknown GLib error.";
531 }
532 string message =
533 base::StringPrintf("GError(%d): %s",
534 (*error)->code,
535 (*error)->message ? (*error)->message : "(unknown)");
536 g_error_free(*error);
537 *error = NULL;
538 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700539}
540
Darin Petkov296889c2010-07-23 16:20:54 -0700541bool Reboot() {
542 vector<string> command;
543 command.push_back("/sbin/shutdown");
544 command.push_back("-r");
545 command.push_back("now");
546 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700547 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700548 TEST_AND_RETURN_FALSE(rc == 0);
549 return true;
550}
551
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800552namespace {
553// Do the actual trigger. We do it as a main-loop callback to (try to) get a
554// consistent stack trace.
555gboolean TriggerCrashReporterUpload(void* unused) {
556 pid_t pid = fork();
557 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
558 if (pid == 0) {
559 // We are the child. Crash.
560 abort(); // never returns
561 }
562 // We are the parent. Wait for child to terminate.
563 pid_t result = waitpid(pid, NULL, 0);
564 LOG_IF(ERROR, result < 0) << "waitpid() failed";
565 return FALSE; // Don't call this callback again
566}
567} // namespace {}
568
569void ScheduleCrashReporterUpload() {
570 g_idle_add(&TriggerCrashReporterUpload, NULL);
571}
572
Darin Petkovc6c135c2010-08-11 13:36:18 -0700573bool SetProcessPriority(ProcessPriority priority) {
574 int prio = static_cast<int>(priority);
575 LOG(INFO) << "Setting process priority to " << prio;
576 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
577 return true;
578}
579
580int ComparePriorities(ProcessPriority priority_lhs,
581 ProcessPriority priority_rhs) {
582 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
583}
584
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700585int FuzzInt(int value, unsigned int range) {
586 int min = value - range / 2;
587 int max = value + range - range / 2;
588 return base::RandInt(min, max);
589}
590
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800591gboolean GlibRunClosure(gpointer data) {
592 google::protobuf::Closure* callback =
593 reinterpret_cast<google::protobuf::Closure*>(data);
594 callback->Run();
595 return FALSE;
596}
597
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700598string FormatSecs(unsigned secs) {
599 return FormatTimeDelta(base::TimeDelta::FromSeconds(secs));
600}
601
602string FormatTimeDelta(base::TimeDelta delta) {
603 // Canonicalize into days, hours, minutes, seconds and microseconds.
604 unsigned days = delta.InDays();
605 delta -= base::TimeDelta::FromDays(days);
606 unsigned hours = delta.InHours();
607 delta -= base::TimeDelta::FromHours(hours);
608 unsigned mins = delta.InMinutes();
609 delta -= base::TimeDelta::FromMinutes(mins);
610 unsigned secs = delta.InSeconds();
611 delta -= base::TimeDelta::FromSeconds(secs);
612 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800613
614 // Construct and return string.
615 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700616 if (days)
617 base::StringAppendF(&str, "%ud", days);
618 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800619 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700620 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800621 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700622 base::StringAppendF(&str, "%u", secs);
623 if (usecs) {
624 int width = 6;
625 while ((usecs / 10) * 10 == usecs) {
626 usecs /= 10;
627 width--;
628 }
629 base::StringAppendF(&str, ".%0*u", width, usecs);
630 }
631 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800632 return str;
633}
634
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700635string ToString(const Time utc_time) {
636 Time::Exploded exp_time;
637 utc_time.UTCExplode(&exp_time);
638 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
639 exp_time.month,
640 exp_time.day_of_month,
641 exp_time.year,
642 exp_time.hour,
643 exp_time.minute,
644 exp_time.second);
645}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000646
647} // namespace utils
648
649} // namespace chromeos_update_engine