blob: 323206181c6be74492eeed2890daad1d0bb3eb61 [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>
27#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040028#include <base/stringprintf.h>
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -080029#include <google/protobuf/stubs/common.h>
Will Drewry8f71da82010-08-30 14:07:11 -050030#include <rootdev/rootdev.h>
31
Andrew de los Reyes970bb282009-12-09 16:34:04 -080032#include "update_engine/file_writer.h"
Darin Petkov33d30642010-08-04 10:18:57 -070033#include "update_engine/omaha_request_params.h"
Darin Petkov296889c2010-07-23 16:20:54 -070034#include "update_engine/subprocess.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000035
36using std::min;
37using std::string;
38using std::vector;
39
40namespace chromeos_update_engine {
41
42namespace utils {
43
Darin Petkov2a0e6332010-09-24 14:43:41 -070044static const char kOOBECompletedMarker[] = "/home/chronos/.oobe_completed";
Darin Petkova07586b2010-10-20 13:41:15 -070045static const char kDevImageMarker[] = "/root/.dev_mode";
Darin Petkov2a0e6332010-09-24 14:43:41 -070046
Darin Petkov33d30642010-08-04 10:18:57 -070047bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070048 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070049}
50
Darin Petkov2a0e6332010-09-24 14:43:41 -070051bool IsOOBEComplete() {
52 return file_util::PathExists(FilePath(kOOBECompletedMarker));
53}
54
Darin Petkovc91dd6b2011-01-10 12:31:34 -080055bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070056 // TODO(petkov): Convert to a library call once a crossystem library is
57 // available (crosbug.com/13291).
58 int exit_code = 0;
59 vector<string> cmd(1, "/usr/bin/crossystem");
60 cmd.push_back("devsw_boot?1");
61
62 // Assume dev mode if the dev switch is set to 1 and there was no error
63 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070064 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070065 bool dev_mode = success && exit_code == 0;
66 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
67 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080068}
69
Darin Petkovf2065b42011-05-17 16:36:27 -070070string GetHardwareClass() {
71 // TODO(petkov): Convert to a library call once a crossystem library is
72 // available (crosbug.com/13291).
73 int exit_code = 0;
74 vector<string> cmd(1, "/usr/bin/crossystem");
75 cmd.push_back("hwid");
76
77 string hwid;
78 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
79 if (success && !exit_code) {
80 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
81 return hwid;
82 }
83 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
84 return "";
85}
86
Andrew de los Reyes970bb282009-12-09 16:34:04 -080087bool WriteFile(const char* path, const char* data, int data_len) {
88 DirectFileWriter writer;
89 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
90 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -070091 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -080092 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -080093 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -080094 return true;
95}
96
Andrew de los Reyes09e56d62010-04-23 13:45:53 -070097bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -070098 const char* c_buf = static_cast<const char*>(buf);
99 ssize_t bytes_written = 0;
100 while (bytes_written < static_cast<ssize_t>(count)) {
101 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
102 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
103 bytes_written += rc;
104 }
105 return true;
106}
107
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700108bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
109 const char* c_buf = static_cast<const char*>(buf);
110 ssize_t bytes_written = 0;
111 while (bytes_written < static_cast<ssize_t>(count)) {
112 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
113 offset + bytes_written);
114 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
115 bytes_written += rc;
116 }
117 return true;
118}
119
120bool PReadAll(int fd, void* buf, size_t count, off_t offset,
121 ssize_t* out_bytes_read) {
122 char* c_buf = static_cast<char*>(buf);
123 ssize_t bytes_read = 0;
124 while (bytes_read < static_cast<ssize_t>(count)) {
125 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
126 offset + bytes_read);
127 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
128 if (rc == 0) {
129 break;
130 }
131 bytes_read += rc;
132 }
133 *out_bytes_read = bytes_read;
134 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700135
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700136}
137
adlr@google.com3defe6a2009-12-04 20:57:17 +0000138bool ReadFile(const std::string& path, std::vector<char>* out) {
139 CHECK(out);
140 FILE* fp = fopen(path.c_str(), "r");
141 if (!fp)
142 return false;
143 const size_t kChunkSize = 1024;
144 size_t read_size;
145 do {
146 char buf[kChunkSize];
147 read_size = fread(buf, 1, kChunkSize, fp);
148 if (read_size == 0)
149 break;
150 out->insert(out->end(), buf, buf + read_size);
151 } while (read_size == kChunkSize);
152 bool success = !ferror(fp);
153 TEST_AND_RETURN_FALSE_ERRNO(fclose(fp) == 0);
154 return success;
155}
156
157bool ReadFileToString(const std::string& path, std::string* out) {
158 vector<char> data;
159 bool success = ReadFile(path, &data);
160 if (!success) {
161 return false;
162 }
163 (*out) = string(&data[0], data.size());
164 return true;
165}
166
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700167off_t FileSize(const string& path) {
168 struct stat stbuf;
169 int rc = stat(path.c_str(), &stbuf);
170 CHECK_EQ(rc, 0);
171 if (rc < 0)
172 return rc;
173 return stbuf.st_size;
174}
175
adlr@google.com3defe6a2009-12-04 20:57:17 +0000176void HexDumpArray(const unsigned char* const arr, const size_t length) {
177 const unsigned char* const char_arr =
178 reinterpret_cast<const unsigned char* const>(arr);
179 LOG(INFO) << "Logging array of length: " << length;
180 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700181 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000182 const unsigned int bytes_remaining = length - i;
183 const unsigned int bytes_per_this_line = min(bytes_per_line,
184 bytes_remaining);
185 char header[100];
186 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
187 TEST_AND_RETURN(r == 13);
188 string line = header;
189 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
190 char buf[20];
191 unsigned char c = char_arr[i + j];
192 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
193 TEST_AND_RETURN(r == 3);
194 line += buf;
195 }
196 LOG(INFO) << line;
197 }
198}
199
200namespace {
201class ScopedDirCloser {
202 public:
203 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
204 ~ScopedDirCloser() {
205 if (dir_ && *dir_) {
206 int r = closedir(*dir_);
207 TEST_AND_RETURN_ERRNO(r == 0);
208 *dir_ = NULL;
209 dir_ = NULL;
210 }
211 }
212 private:
213 DIR** dir_;
214};
215} // namespace {}
216
217bool RecursiveUnlinkDir(const std::string& path) {
218 struct stat stbuf;
219 int r = lstat(path.c_str(), &stbuf);
220 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
221 if ((r < 0) && (errno == ENOENT))
222 // path request is missing. that's fine.
223 return true;
224 if (!S_ISDIR(stbuf.st_mode)) {
225 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700226 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000227 // success or path disappeared before we could unlink.
228 return true;
229 }
230 {
231 // We have a dir, unlink all children, then delete dir
232 DIR *dir = opendir(path.c_str());
233 TEST_AND_RETURN_FALSE_ERRNO(dir);
234 ScopedDirCloser dir_closer(&dir);
235 struct dirent dir_entry;
236 struct dirent *dir_entry_p;
237 int err = 0;
238 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
239 if (dir_entry_p == NULL) {
240 // end of stream reached
241 break;
242 }
243 // Skip . and ..
244 if (!strcmp(dir_entry_p->d_name, ".") ||
245 !strcmp(dir_entry_p->d_name, ".."))
246 continue;
247 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700248 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000249 }
250 TEST_AND_RETURN_FALSE(err == 0);
251 }
252 // unlink dir
253 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
254 return true;
255}
256
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700257string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700258 FilePath device_path(partition_device);
259 if (device_path.DirName().value() != "/dev") {
260 return "";
261 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700262 string::const_iterator it = --partition_device.end();
263 for (; it >= partition_device.begin(); --it) {
264 if (!isdigit(*it))
265 break;
266 }
267 // Some devices contain a p before the partitions. For example:
268 // /dev/mmc0p4 should be shortened to /dev/mmc0.
269 if (*it == 'p')
270 --it;
271 return string(partition_device.begin(), it + 1);
272}
273
274string PartitionNumber(const string& partition_device) {
275 CHECK(!partition_device.empty());
276 string::const_iterator it = --partition_device.end();
277 for (; it >= partition_device.begin(); --it) {
278 if (!isdigit(*it))
279 break;
280 }
281 return string(it + 1, partition_device.end());
282}
283
Darin Petkovf74eb652010-08-04 12:08:38 -0700284string SysfsBlockDevice(const string& device) {
285 FilePath device_path(device);
286 if (device_path.DirName().value() != "/dev") {
287 return "";
288 }
289 return FilePath("/sys/block").Append(device_path.BaseName()).value();
290}
291
292bool IsRemovableDevice(const std::string& device) {
293 string sysfs_block = SysfsBlockDevice(device);
294 string removable;
295 if (sysfs_block.empty() ||
296 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
297 &removable)) {
298 return false;
299 }
300 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
301 return removable == "1";
302}
303
adlr@google.com3defe6a2009-12-04 20:57:17 +0000304std::string ErrnoNumberAsString(int err) {
305 char buf[100];
306 buf[0] = '\0';
307 return strerror_r(err, buf, sizeof(buf));
308}
309
310std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
311 string ret;
312 bool last_insert_was_slash = false;
313 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
314 if (*it == '/') {
315 if (last_insert_was_slash)
316 continue;
317 last_insert_was_slash = true;
318 } else {
319 last_insert_was_slash = false;
320 }
321 ret.push_back(*it);
322 }
323 if (strip_trailing_slash && last_insert_was_slash) {
324 string::size_type last_non_slash = ret.find_last_not_of('/');
325 if (last_non_slash != string::npos) {
326 ret.resize(last_non_slash + 1);
327 } else {
328 ret = "";
329 }
330 }
331 return ret;
332}
333
334bool FileExists(const char* path) {
335 struct stat stbuf;
336 return 0 == lstat(path, &stbuf);
337}
338
Darin Petkov30291ed2010-11-12 10:23:06 -0800339bool IsSymlink(const char* path) {
340 struct stat stbuf;
341 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
342}
343
adlr@google.com3defe6a2009-12-04 20:57:17 +0000344std::string TempFilename(string path) {
345 static const string suffix("XXXXXX");
346 CHECK(StringHasSuffix(path, suffix));
347 do {
348 string new_suffix;
349 for (unsigned int i = 0; i < suffix.size(); i++) {
350 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
351 if (r < 26)
352 new_suffix.append(1, 'a' + r);
353 else if (r < (26 * 2))
354 new_suffix.append(1, 'A' + r - 26);
355 else
356 new_suffix.append(1, '0' + r - (26 * 2));
357 }
358 CHECK_EQ(new_suffix.size(), suffix.size());
359 path.resize(path.size() - new_suffix.size());
360 path.append(new_suffix);
361 } while (FileExists(path.c_str()));
362 return path;
363}
364
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700365bool MakeTempFile(const std::string& filename_template,
366 std::string* filename,
367 int* fd) {
368 DCHECK(filename || fd);
369 vector<char> buf(filename_template.size() + 1);
370 memcpy(&buf[0], filename_template.data(), filename_template.size());
371 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700372
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700373 int mkstemp_fd = mkstemp(&buf[0]);
374 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
375 if (filename) {
376 *filename = &buf[0];
377 }
378 if (fd) {
379 *fd = mkstemp_fd;
380 } else {
381 close(mkstemp_fd);
382 }
383 return true;
384}
385
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700386bool MakeTempDirectory(const std::string& dirname_template,
387 std::string* dirname) {
388 DCHECK(dirname);
389 vector<char> buf(dirname_template.size() + 1);
390 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
391 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700392
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700393 char* return_code = mkdtemp(&buf[0]);
394 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
395 *dirname = &buf[0];
396 return true;
397}
398
adlr@google.com3defe6a2009-12-04 20:57:17 +0000399bool StringHasSuffix(const std::string& str, const std::string& suffix) {
400 if (suffix.size() > str.size())
401 return false;
402 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
403}
404
405bool StringHasPrefix(const std::string& str, const std::string& prefix) {
406 if (prefix.size() > str.size())
407 return false;
408 return 0 == str.compare(0, prefix.size(), prefix);
409}
410
Will Drewry8f71da82010-08-30 14:07:11 -0500411const std::string BootDevice() {
412 char boot_path[PATH_MAX];
413 // Resolve the boot device path fully, including dereferencing
414 // through dm-verity.
415 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
416
417 if (ret < 0) {
418 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000419 return "";
420 }
Will Drewry8f71da82010-08-30 14:07:11 -0500421 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
422
423 // This local variable is used to construct the return string and is not
424 // passed around after use.
425 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000426}
427
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700428const string BootKernelDevice(const std::string& boot_device) {
429 // Currntly this assumes the last digit of the boot device is
430 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
431 // get the kernel device.
432 string ret = boot_device;
433 if (ret.empty())
434 return ret;
435 char last_char = ret[ret.size() - 1];
436 if (last_char == '3' || last_char == '5' || last_char == '7') {
437 ret[ret.size() - 1] = last_char - 1;
438 return ret;
439 }
440 return "";
441}
442
adlr@google.com3defe6a2009-12-04 20:57:17 +0000443bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700444 const string& mountpoint,
445 unsigned long mountflags) {
446 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000447 if (rc < 0) {
448 string msg = ErrnoNumberAsString(errno);
449 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
450 << device << " on " << mountpoint;
451 return false;
452 }
453 return true;
454}
455
456bool UnmountFilesystem(const string& mountpoint) {
457 TEST_AND_RETURN_FALSE_ERRNO(umount(mountpoint.c_str()) == 0);
458 return true;
459}
460
Darin Petkovd3f8c892010-10-12 21:38:45 -0700461bool GetFilesystemSize(const std::string& device,
462 int* out_block_count,
463 int* out_block_size) {
464 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
465 TEST_AND_RETURN_FALSE(fd >= 0);
466 ScopedFdCloser fd_closer(&fd);
467 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
468}
469
470bool GetFilesystemSizeFromFD(int fd,
471 int* out_block_count,
472 int* out_block_size) {
473 TEST_AND_RETURN_FALSE(fd >= 0);
474
475 // Determine the ext3 filesystem size by directly reading the block count and
476 // block size information from the superblock. See include/linux/ext3_fs.h for
477 // more details on the structure.
478 ssize_t kBufferSize = 16 * sizeof(uint32_t);
479 char buffer[kBufferSize];
480 const int kSuperblockOffset = 1024;
481 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
482 kBufferSize) {
483 PLOG(ERROR) << "Unable to determine file system size:";
484 return false;
485 }
486 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
487 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
488 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
489 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
490 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
491 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
492 block_count = le32toh(block_count);
493 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
494 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
495 magic = le16toh(magic);
496
497 // Sanity check the parameters.
498 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
499 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
500 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
501 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
502 int block_size = 1 << log_block_size;
503 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
504 block_size <= kExt3MaxBlockSize);
505 TEST_AND_RETURN_FALSE(block_count > 0);
506
507 if (out_block_count) {
508 *out_block_count = block_count;
509 }
510 if (out_block_size) {
511 *out_block_size = block_size;
512 }
513 return true;
514}
515
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700516bool GetBootloader(BootLoader* out_bootloader) {
517 // For now, hardcode to syslinux.
518 *out_bootloader = BootLoader_SYSLINUX;
519 return true;
520}
521
Darin Petkova0b9e772011-10-06 05:05:56 -0700522string GetAndFreeGError(GError** error) {
523 if (!*error) {
524 return "Unknown GLib error.";
525 }
526 string message =
527 base::StringPrintf("GError(%d): %s",
528 (*error)->code,
529 (*error)->message ? (*error)->message : "(unknown)");
530 g_error_free(*error);
531 *error = NULL;
532 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700533}
534
Darin Petkov296889c2010-07-23 16:20:54 -0700535bool Reboot() {
536 vector<string> command;
537 command.push_back("/sbin/shutdown");
538 command.push_back("-r");
539 command.push_back("now");
540 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700541 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700542 TEST_AND_RETURN_FALSE(rc == 0);
543 return true;
544}
545
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800546namespace {
547// Do the actual trigger. We do it as a main-loop callback to (try to) get a
548// consistent stack trace.
549gboolean TriggerCrashReporterUpload(void* unused) {
550 pid_t pid = fork();
551 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
552 if (pid == 0) {
553 // We are the child. Crash.
554 abort(); // never returns
555 }
556 // We are the parent. Wait for child to terminate.
557 pid_t result = waitpid(pid, NULL, 0);
558 LOG_IF(ERROR, result < 0) << "waitpid() failed";
559 return FALSE; // Don't call this callback again
560}
561} // namespace {}
562
563void ScheduleCrashReporterUpload() {
564 g_idle_add(&TriggerCrashReporterUpload, NULL);
565}
566
Darin Petkovc6c135c2010-08-11 13:36:18 -0700567bool SetProcessPriority(ProcessPriority priority) {
568 int prio = static_cast<int>(priority);
569 LOG(INFO) << "Setting process priority to " << prio;
570 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
571 return true;
572}
573
574int ComparePriorities(ProcessPriority priority_lhs,
575 ProcessPriority priority_rhs) {
576 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
577}
578
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700579int FuzzInt(int value, unsigned int range) {
580 int min = value - range / 2;
581 int max = value + range - range / 2;
582 return base::RandInt(min, max);
583}
584
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800585gboolean GlibRunClosure(gpointer data) {
586 google::protobuf::Closure* callback =
587 reinterpret_cast<google::protobuf::Closure*>(data);
588 callback->Run();
589 return FALSE;
590}
591
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800592string SecsToHourMinSecStr(unsigned secs) {
593 // Canonicalize into hours, minutes, seconds.
594 unsigned hours = secs / (60 * 60);
595 secs -= hours * (60 * 60);
596 unsigned mins = secs / 60;
597 secs -= mins * 60;
598
599 // Construct and return string.
600 string str;
601 if (hours)
602 base::StringAppendF(&str, "%uh", hours);
603 if (hours || mins)
604 base::StringAppendF(&str, "%um", mins);
605 base::StringAppendF(&str, "%us", secs);
606 return str;
607}
608
Andrew de los Reyes4fe15d02009-12-10 19:01:36 -0800609const char* const kStatefulPartition = "/mnt/stateful_partition";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000610
611} // namespace utils
612
613} // namespace chromeos_update_engine