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