blob: f4b3b244afafe7e9a2a472b280380dc27f4171f9 [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);
108 ssize_t bytes_written = 0;
109 while (bytes_written < static_cast<ssize_t>(count)) {
110 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
111 offset + bytes_written);
112 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
113 bytes_written += rc;
114 }
115 return true;
116}
117
118bool PReadAll(int fd, void* buf, size_t count, off_t offset,
119 ssize_t* out_bytes_read) {
120 char* c_buf = static_cast<char*>(buf);
121 ssize_t bytes_read = 0;
122 while (bytes_read < static_cast<ssize_t>(count)) {
123 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
124 offset + bytes_read);
125 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
126 if (rc == 0) {
127 break;
128 }
129 bytes_read += rc;
130 }
131 *out_bytes_read = bytes_read;
132 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700133
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700134}
135
adlr@google.com3defe6a2009-12-04 20:57:17 +0000136bool ReadFile(const std::string& path, std::vector<char>* out) {
137 CHECK(out);
138 FILE* fp = fopen(path.c_str(), "r");
139 if (!fp)
140 return false;
141 const size_t kChunkSize = 1024;
142 size_t read_size;
143 do {
144 char buf[kChunkSize];
145 read_size = fread(buf, 1, kChunkSize, fp);
146 if (read_size == 0)
147 break;
148 out->insert(out->end(), buf, buf + read_size);
149 } while (read_size == kChunkSize);
150 bool success = !ferror(fp);
151 TEST_AND_RETURN_FALSE_ERRNO(fclose(fp) == 0);
152 return success;
153}
154
155bool ReadFileToString(const std::string& path, std::string* out) {
156 vector<char> data;
157 bool success = ReadFile(path, &data);
158 if (!success) {
159 return false;
160 }
161 (*out) = string(&data[0], data.size());
162 return true;
163}
164
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700165off_t FileSize(const string& path) {
166 struct stat stbuf;
167 int rc = stat(path.c_str(), &stbuf);
168 CHECK_EQ(rc, 0);
169 if (rc < 0)
170 return rc;
171 return stbuf.st_size;
172}
173
adlr@google.com3defe6a2009-12-04 20:57:17 +0000174void HexDumpArray(const unsigned char* const arr, const size_t length) {
175 const unsigned char* const char_arr =
176 reinterpret_cast<const unsigned char* const>(arr);
177 LOG(INFO) << "Logging array of length: " << length;
178 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700179 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000180 const unsigned int bytes_remaining = length - i;
181 const unsigned int bytes_per_this_line = min(bytes_per_line,
182 bytes_remaining);
183 char header[100];
184 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
185 TEST_AND_RETURN(r == 13);
186 string line = header;
187 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
188 char buf[20];
189 unsigned char c = char_arr[i + j];
190 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
191 TEST_AND_RETURN(r == 3);
192 line += buf;
193 }
194 LOG(INFO) << line;
195 }
196}
197
198namespace {
199class ScopedDirCloser {
200 public:
201 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
202 ~ScopedDirCloser() {
203 if (dir_ && *dir_) {
204 int r = closedir(*dir_);
205 TEST_AND_RETURN_ERRNO(r == 0);
206 *dir_ = NULL;
207 dir_ = NULL;
208 }
209 }
210 private:
211 DIR** dir_;
212};
213} // namespace {}
214
215bool RecursiveUnlinkDir(const std::string& path) {
216 struct stat stbuf;
217 int r = lstat(path.c_str(), &stbuf);
218 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
219 if ((r < 0) && (errno == ENOENT))
220 // path request is missing. that's fine.
221 return true;
222 if (!S_ISDIR(stbuf.st_mode)) {
223 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700224 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000225 // success or path disappeared before we could unlink.
226 return true;
227 }
228 {
229 // We have a dir, unlink all children, then delete dir
230 DIR *dir = opendir(path.c_str());
231 TEST_AND_RETURN_FALSE_ERRNO(dir);
232 ScopedDirCloser dir_closer(&dir);
233 struct dirent dir_entry;
234 struct dirent *dir_entry_p;
235 int err = 0;
236 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
237 if (dir_entry_p == NULL) {
238 // end of stream reached
239 break;
240 }
241 // Skip . and ..
242 if (!strcmp(dir_entry_p->d_name, ".") ||
243 !strcmp(dir_entry_p->d_name, ".."))
244 continue;
245 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700246 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000247 }
248 TEST_AND_RETURN_FALSE(err == 0);
249 }
250 // unlink dir
251 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
252 return true;
253}
254
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700255string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700256 FilePath device_path(partition_device);
257 if (device_path.DirName().value() != "/dev") {
258 return "";
259 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700260 string::const_iterator it = --partition_device.end();
261 for (; it >= partition_device.begin(); --it) {
262 if (!isdigit(*it))
263 break;
264 }
265 // Some devices contain a p before the partitions. For example:
266 // /dev/mmc0p4 should be shortened to /dev/mmc0.
267 if (*it == 'p')
268 --it;
269 return string(partition_device.begin(), it + 1);
270}
271
272string PartitionNumber(const string& partition_device) {
273 CHECK(!partition_device.empty());
274 string::const_iterator it = --partition_device.end();
275 for (; it >= partition_device.begin(); --it) {
276 if (!isdigit(*it))
277 break;
278 }
279 return string(it + 1, partition_device.end());
280}
281
Darin Petkovf74eb652010-08-04 12:08:38 -0700282string SysfsBlockDevice(const string& device) {
283 FilePath device_path(device);
284 if (device_path.DirName().value() != "/dev") {
285 return "";
286 }
287 return FilePath("/sys/block").Append(device_path.BaseName()).value();
288}
289
290bool IsRemovableDevice(const std::string& device) {
291 string sysfs_block = SysfsBlockDevice(device);
292 string removable;
293 if (sysfs_block.empty() ||
294 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
295 &removable)) {
296 return false;
297 }
298 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
299 return removable == "1";
300}
301
adlr@google.com3defe6a2009-12-04 20:57:17 +0000302std::string ErrnoNumberAsString(int err) {
303 char buf[100];
304 buf[0] = '\0';
305 return strerror_r(err, buf, sizeof(buf));
306}
307
308std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
309 string ret;
310 bool last_insert_was_slash = false;
311 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
312 if (*it == '/') {
313 if (last_insert_was_slash)
314 continue;
315 last_insert_was_slash = true;
316 } else {
317 last_insert_was_slash = false;
318 }
319 ret.push_back(*it);
320 }
321 if (strip_trailing_slash && last_insert_was_slash) {
322 string::size_type last_non_slash = ret.find_last_not_of('/');
323 if (last_non_slash != string::npos) {
324 ret.resize(last_non_slash + 1);
325 } else {
326 ret = "";
327 }
328 }
329 return ret;
330}
331
332bool FileExists(const char* path) {
333 struct stat stbuf;
334 return 0 == lstat(path, &stbuf);
335}
336
Darin Petkov30291ed2010-11-12 10:23:06 -0800337bool IsSymlink(const char* path) {
338 struct stat stbuf;
339 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
340}
341
adlr@google.com3defe6a2009-12-04 20:57:17 +0000342std::string TempFilename(string path) {
343 static const string suffix("XXXXXX");
344 CHECK(StringHasSuffix(path, suffix));
345 do {
346 string new_suffix;
347 for (unsigned int i = 0; i < suffix.size(); i++) {
348 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
349 if (r < 26)
350 new_suffix.append(1, 'a' + r);
351 else if (r < (26 * 2))
352 new_suffix.append(1, 'A' + r - 26);
353 else
354 new_suffix.append(1, '0' + r - (26 * 2));
355 }
356 CHECK_EQ(new_suffix.size(), suffix.size());
357 path.resize(path.size() - new_suffix.size());
358 path.append(new_suffix);
359 } while (FileExists(path.c_str()));
360 return path;
361}
362
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700363bool MakeTempFile(const std::string& filename_template,
364 std::string* filename,
365 int* fd) {
366 DCHECK(filename || fd);
367 vector<char> buf(filename_template.size() + 1);
368 memcpy(&buf[0], filename_template.data(), filename_template.size());
369 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700370
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700371 int mkstemp_fd = mkstemp(&buf[0]);
372 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
373 if (filename) {
374 *filename = &buf[0];
375 }
376 if (fd) {
377 *fd = mkstemp_fd;
378 } else {
379 close(mkstemp_fd);
380 }
381 return true;
382}
383
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700384bool MakeTempDirectory(const std::string& dirname_template,
385 std::string* dirname) {
386 DCHECK(dirname);
387 vector<char> buf(dirname_template.size() + 1);
388 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
389 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700390
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700391 char* return_code = mkdtemp(&buf[0]);
392 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
393 *dirname = &buf[0];
394 return true;
395}
396
adlr@google.com3defe6a2009-12-04 20:57:17 +0000397bool StringHasSuffix(const std::string& str, const std::string& suffix) {
398 if (suffix.size() > str.size())
399 return false;
400 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
401}
402
403bool StringHasPrefix(const std::string& str, const std::string& prefix) {
404 if (prefix.size() > str.size())
405 return false;
406 return 0 == str.compare(0, prefix.size(), prefix);
407}
408
Will Drewry8f71da82010-08-30 14:07:11 -0500409const std::string BootDevice() {
410 char boot_path[PATH_MAX];
411 // Resolve the boot device path fully, including dereferencing
412 // through dm-verity.
413 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
414
415 if (ret < 0) {
416 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000417 return "";
418 }
Will Drewry8f71da82010-08-30 14:07:11 -0500419 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
420
421 // This local variable is used to construct the return string and is not
422 // passed around after use.
423 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000424}
425
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700426const string BootKernelDevice(const std::string& boot_device) {
427 // Currntly this assumes the last digit of the boot device is
428 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
429 // get the kernel device.
430 string ret = boot_device;
431 if (ret.empty())
432 return ret;
433 char last_char = ret[ret.size() - 1];
434 if (last_char == '3' || last_char == '5' || last_char == '7') {
435 ret[ret.size() - 1] = last_char - 1;
436 return ret;
437 }
438 return "";
439}
440
adlr@google.com3defe6a2009-12-04 20:57:17 +0000441bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700442 const string& mountpoint,
443 unsigned long mountflags) {
444 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000445 if (rc < 0) {
446 string msg = ErrnoNumberAsString(errno);
447 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
448 << device << " on " << mountpoint;
449 return false;
450 }
451 return true;
452}
453
454bool UnmountFilesystem(const string& mountpoint) {
455 TEST_AND_RETURN_FALSE_ERRNO(umount(mountpoint.c_str()) == 0);
456 return true;
457}
458
Darin Petkovd3f8c892010-10-12 21:38:45 -0700459bool GetFilesystemSize(const std::string& device,
460 int* out_block_count,
461 int* out_block_size) {
462 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
463 TEST_AND_RETURN_FALSE(fd >= 0);
464 ScopedFdCloser fd_closer(&fd);
465 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
466}
467
468bool GetFilesystemSizeFromFD(int fd,
469 int* out_block_count,
470 int* out_block_size) {
471 TEST_AND_RETURN_FALSE(fd >= 0);
472
473 // Determine the ext3 filesystem size by directly reading the block count and
474 // block size information from the superblock. See include/linux/ext3_fs.h for
475 // more details on the structure.
476 ssize_t kBufferSize = 16 * sizeof(uint32_t);
477 char buffer[kBufferSize];
478 const int kSuperblockOffset = 1024;
479 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
480 kBufferSize) {
481 PLOG(ERROR) << "Unable to determine file system size:";
482 return false;
483 }
484 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
485 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
486 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
487 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
488 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
489 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
490 block_count = le32toh(block_count);
491 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
492 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
493 magic = le16toh(magic);
494
495 // Sanity check the parameters.
496 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
497 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
498 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
499 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
500 int block_size = 1 << log_block_size;
501 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
502 block_size <= kExt3MaxBlockSize);
503 TEST_AND_RETURN_FALSE(block_count > 0);
504
505 if (out_block_count) {
506 *out_block_count = block_count;
507 }
508 if (out_block_size) {
509 *out_block_size = block_size;
510 }
511 return true;
512}
513
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700514bool GetBootloader(BootLoader* out_bootloader) {
515 // For now, hardcode to syslinux.
516 *out_bootloader = BootLoader_SYSLINUX;
517 return true;
518}
519
Darin Petkova0b9e772011-10-06 05:05:56 -0700520string GetAndFreeGError(GError** error) {
521 if (!*error) {
522 return "Unknown GLib error.";
523 }
524 string message =
525 base::StringPrintf("GError(%d): %s",
526 (*error)->code,
527 (*error)->message ? (*error)->message : "(unknown)");
528 g_error_free(*error);
529 *error = NULL;
530 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700531}
532
Darin Petkov296889c2010-07-23 16:20:54 -0700533bool Reboot() {
534 vector<string> command;
535 command.push_back("/sbin/shutdown");
536 command.push_back("-r");
537 command.push_back("now");
538 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700539 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700540 TEST_AND_RETURN_FALSE(rc == 0);
541 return true;
542}
543
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800544namespace {
545// Do the actual trigger. We do it as a main-loop callback to (try to) get a
546// consistent stack trace.
547gboolean TriggerCrashReporterUpload(void* unused) {
548 pid_t pid = fork();
549 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
550 if (pid == 0) {
551 // We are the child. Crash.
552 abort(); // never returns
553 }
554 // We are the parent. Wait for child to terminate.
555 pid_t result = waitpid(pid, NULL, 0);
556 LOG_IF(ERROR, result < 0) << "waitpid() failed";
557 return FALSE; // Don't call this callback again
558}
559} // namespace {}
560
561void ScheduleCrashReporterUpload() {
562 g_idle_add(&TriggerCrashReporterUpload, NULL);
563}
564
Darin Petkovc6c135c2010-08-11 13:36:18 -0700565bool SetProcessPriority(ProcessPriority priority) {
566 int prio = static_cast<int>(priority);
567 LOG(INFO) << "Setting process priority to " << prio;
568 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
569 return true;
570}
571
572int ComparePriorities(ProcessPriority priority_lhs,
573 ProcessPriority priority_rhs) {
574 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
575}
576
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700577int FuzzInt(int value, unsigned int range) {
578 int min = value - range / 2;
579 int max = value + range - range / 2;
580 return base::RandInt(min, max);
581}
582
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800583gboolean GlibRunClosure(gpointer data) {
584 google::protobuf::Closure* callback =
585 reinterpret_cast<google::protobuf::Closure*>(data);
586 callback->Run();
587 return FALSE;
588}
589
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700590string FormatSecs(unsigned secs) {
591 return FormatTimeDelta(base::TimeDelta::FromSeconds(secs));
592}
593
594string FormatTimeDelta(base::TimeDelta delta) {
595 // Canonicalize into days, hours, minutes, seconds and microseconds.
596 unsigned days = delta.InDays();
597 delta -= base::TimeDelta::FromDays(days);
598 unsigned hours = delta.InHours();
599 delta -= base::TimeDelta::FromHours(hours);
600 unsigned mins = delta.InMinutes();
601 delta -= base::TimeDelta::FromMinutes(mins);
602 unsigned secs = delta.InSeconds();
603 delta -= base::TimeDelta::FromSeconds(secs);
604 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800605
606 // Construct and return string.
607 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700608 if (days)
609 base::StringAppendF(&str, "%ud", days);
610 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800611 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700612 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800613 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700614 base::StringAppendF(&str, "%u", secs);
615 if (usecs) {
616 int width = 6;
617 while ((usecs / 10) * 10 == usecs) {
618 usecs /= 10;
619 width--;
620 }
621 base::StringAppendF(&str, ".%0*u", width, usecs);
622 }
623 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800624 return str;
625}
626
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700627string ToString(const Time utc_time) {
628 Time::Exploded exp_time;
629 utc_time.UTCExplode(&exp_time);
630 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
631 exp_time.month,
632 exp_time.day_of_month,
633 exp_time.year,
634 exp_time.hour,
635 exp_time.minute,
636 exp_time.second);
637}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000638
639} // namespace utils
640
641} // namespace chromeos_update_engine