blob: 769d7fe4f9828d6eba45ae7c7e224ce60f1ceda9 [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
Jay Srinivasan08fce042012-06-07 16:31:01 -070044static const char kOOBECompletedMarker[] = "/home/chronos/.oobe_completed";
45
46bool RealSystemState::IsOOBEComplete() {
47 return file_util::PathExists(FilePath(kOOBECompletedMarker));
48}
49
adlr@google.com3defe6a2009-12-04 20:57:17 +000050namespace utils {
51
Darin Petkova07586b2010-10-20 13:41:15 -070052static const char kDevImageMarker[] = "/root/.dev_mode";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070053const char* const kStatefulPartition = "/mnt/stateful_partition";
Darin Petkov2a0e6332010-09-24 14:43:41 -070054
Darin Petkov33d30642010-08-04 10:18:57 -070055bool IsOfficialBuild() {
Darin Petkova07586b2010-10-20 13:41:15 -070056 return !file_util::PathExists(FilePath(kDevImageMarker));
Darin Petkov33d30642010-08-04 10:18:57 -070057}
58
Darin Petkovc91dd6b2011-01-10 12:31:34 -080059bool IsNormalBootMode() {
Darin Petkov44d98d92011-03-21 16:08:11 -070060 // TODO(petkov): Convert to a library call once a crossystem library is
61 // available (crosbug.com/13291).
62 int exit_code = 0;
63 vector<string> cmd(1, "/usr/bin/crossystem");
64 cmd.push_back("devsw_boot?1");
65
66 // Assume dev mode if the dev switch is set to 1 and there was no error
67 // executing crossystem. Assume normal mode otherwise.
Darin Petkov85d02b72011-05-17 13:25:51 -070068 bool success = Subprocess::SynchronousExec(cmd, &exit_code, NULL);
Darin Petkov44d98d92011-03-21 16:08:11 -070069 bool dev_mode = success && exit_code == 0;
70 LOG_IF(INFO, dev_mode) << "Booted in dev mode.";
71 return !dev_mode;
Darin Petkovc91dd6b2011-01-10 12:31:34 -080072}
73
Darin Petkovf2065b42011-05-17 16:36:27 -070074string GetHardwareClass() {
75 // TODO(petkov): Convert to a library call once a crossystem library is
76 // available (crosbug.com/13291).
77 int exit_code = 0;
78 vector<string> cmd(1, "/usr/bin/crossystem");
79 cmd.push_back("hwid");
80
81 string hwid;
82 bool success = Subprocess::SynchronousExec(cmd, &exit_code, &hwid);
83 if (success && !exit_code) {
84 TrimWhitespaceASCII(hwid, TRIM_ALL, &hwid);
85 return hwid;
86 }
87 LOG(ERROR) << "Unable to read HWID (" << exit_code << ") " << hwid;
88 return "";
89}
90
Andrew de los Reyes970bb282009-12-09 16:34:04 -080091bool WriteFile(const char* path, const char* data, int data_len) {
92 DirectFileWriter writer;
93 TEST_AND_RETURN_FALSE_ERRNO(0 == writer.Open(path,
94 O_WRONLY | O_CREAT | O_TRUNC,
Chris Masone4dc2ada2010-09-23 12:43:03 -070095 0600));
Andrew de los Reyes970bb282009-12-09 16:34:04 -080096 ScopedFileWriterCloser closer(&writer);
Don Garrette410e0f2011-11-10 15:39:01 -080097 TEST_AND_RETURN_FALSE_ERRNO(writer.Write(data, data_len));
Andrew de los Reyes970bb282009-12-09 16:34:04 -080098 return true;
99}
100
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700101bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700102 const char* c_buf = static_cast<const char*>(buf);
103 ssize_t bytes_written = 0;
104 while (bytes_written < static_cast<ssize_t>(count)) {
105 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
106 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
107 bytes_written += rc;
108 }
109 return true;
110}
111
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700112bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
113 const char* c_buf = static_cast<const char*>(buf);
114 ssize_t bytes_written = 0;
115 while (bytes_written < static_cast<ssize_t>(count)) {
116 ssize_t rc = pwrite(fd, c_buf + bytes_written, count - bytes_written,
117 offset + bytes_written);
118 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
119 bytes_written += rc;
120 }
121 return true;
122}
123
124bool PReadAll(int fd, void* buf, size_t count, off_t offset,
125 ssize_t* out_bytes_read) {
126 char* c_buf = static_cast<char*>(buf);
127 ssize_t bytes_read = 0;
128 while (bytes_read < static_cast<ssize_t>(count)) {
129 ssize_t rc = pread(fd, c_buf + bytes_read, count - bytes_read,
130 offset + bytes_read);
131 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
132 if (rc == 0) {
133 break;
134 }
135 bytes_read += rc;
136 }
137 *out_bytes_read = bytes_read;
138 return true;
Darin Petkov296889c2010-07-23 16:20:54 -0700139
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700140}
141
adlr@google.com3defe6a2009-12-04 20:57:17 +0000142bool ReadFile(const std::string& path, std::vector<char>* out) {
143 CHECK(out);
144 FILE* fp = fopen(path.c_str(), "r");
145 if (!fp)
146 return false;
147 const size_t kChunkSize = 1024;
148 size_t read_size;
149 do {
150 char buf[kChunkSize];
151 read_size = fread(buf, 1, kChunkSize, fp);
152 if (read_size == 0)
153 break;
154 out->insert(out->end(), buf, buf + read_size);
155 } while (read_size == kChunkSize);
156 bool success = !ferror(fp);
157 TEST_AND_RETURN_FALSE_ERRNO(fclose(fp) == 0);
158 return success;
159}
160
161bool ReadFileToString(const std::string& path, std::string* out) {
162 vector<char> data;
163 bool success = ReadFile(path, &data);
164 if (!success) {
165 return false;
166 }
167 (*out) = string(&data[0], data.size());
168 return true;
169}
170
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700171off_t FileSize(const string& path) {
172 struct stat stbuf;
173 int rc = stat(path.c_str(), &stbuf);
174 CHECK_EQ(rc, 0);
175 if (rc < 0)
176 return rc;
177 return stbuf.st_size;
178}
179
adlr@google.com3defe6a2009-12-04 20:57:17 +0000180void HexDumpArray(const unsigned char* const arr, const size_t length) {
181 const unsigned char* const char_arr =
182 reinterpret_cast<const unsigned char* const>(arr);
183 LOG(INFO) << "Logging array of length: " << length;
184 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700185 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000186 const unsigned int bytes_remaining = length - i;
187 const unsigned int bytes_per_this_line = min(bytes_per_line,
188 bytes_remaining);
189 char header[100];
190 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
191 TEST_AND_RETURN(r == 13);
192 string line = header;
193 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
194 char buf[20];
195 unsigned char c = char_arr[i + j];
196 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
197 TEST_AND_RETURN(r == 3);
198 line += buf;
199 }
200 LOG(INFO) << line;
201 }
202}
203
204namespace {
205class ScopedDirCloser {
206 public:
207 explicit ScopedDirCloser(DIR** dir) : dir_(dir) {}
208 ~ScopedDirCloser() {
209 if (dir_ && *dir_) {
210 int r = closedir(*dir_);
211 TEST_AND_RETURN_ERRNO(r == 0);
212 *dir_ = NULL;
213 dir_ = NULL;
214 }
215 }
216 private:
217 DIR** dir_;
218};
219} // namespace {}
220
221bool RecursiveUnlinkDir(const std::string& path) {
222 struct stat stbuf;
223 int r = lstat(path.c_str(), &stbuf);
224 TEST_AND_RETURN_FALSE_ERRNO((r == 0) || (errno == ENOENT));
225 if ((r < 0) && (errno == ENOENT))
226 // path request is missing. that's fine.
227 return true;
228 if (!S_ISDIR(stbuf.st_mode)) {
229 TEST_AND_RETURN_FALSE_ERRNO((unlink(path.c_str()) == 0) ||
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700230 (errno == ENOENT));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000231 // success or path disappeared before we could unlink.
232 return true;
233 }
234 {
235 // We have a dir, unlink all children, then delete dir
236 DIR *dir = opendir(path.c_str());
237 TEST_AND_RETURN_FALSE_ERRNO(dir);
238 ScopedDirCloser dir_closer(&dir);
239 struct dirent dir_entry;
240 struct dirent *dir_entry_p;
241 int err = 0;
242 while ((err = readdir_r(dir, &dir_entry, &dir_entry_p)) == 0) {
243 if (dir_entry_p == NULL) {
244 // end of stream reached
245 break;
246 }
247 // Skip . and ..
248 if (!strcmp(dir_entry_p->d_name, ".") ||
249 !strcmp(dir_entry_p->d_name, ".."))
250 continue;
251 TEST_AND_RETURN_FALSE(RecursiveUnlinkDir(path + "/" +
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700252 dir_entry_p->d_name));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000253 }
254 TEST_AND_RETURN_FALSE(err == 0);
255 }
256 // unlink dir
257 TEST_AND_RETURN_FALSE_ERRNO((rmdir(path.c_str()) == 0) || (errno == ENOENT));
258 return true;
259}
260
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700261string RootDevice(const string& partition_device) {
Darin Petkovf74eb652010-08-04 12:08:38 -0700262 FilePath device_path(partition_device);
263 if (device_path.DirName().value() != "/dev") {
264 return "";
265 }
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700266 string::const_iterator it = --partition_device.end();
267 for (; it >= partition_device.begin(); --it) {
268 if (!isdigit(*it))
269 break;
270 }
271 // Some devices contain a p before the partitions. For example:
272 // /dev/mmc0p4 should be shortened to /dev/mmc0.
273 if (*it == 'p')
274 --it;
275 return string(partition_device.begin(), it + 1);
276}
277
278string PartitionNumber(const string& partition_device) {
279 CHECK(!partition_device.empty());
280 string::const_iterator it = --partition_device.end();
281 for (; it >= partition_device.begin(); --it) {
282 if (!isdigit(*it))
283 break;
284 }
285 return string(it + 1, partition_device.end());
286}
287
Darin Petkovf74eb652010-08-04 12:08:38 -0700288string SysfsBlockDevice(const string& device) {
289 FilePath device_path(device);
290 if (device_path.DirName().value() != "/dev") {
291 return "";
292 }
293 return FilePath("/sys/block").Append(device_path.BaseName()).value();
294}
295
296bool IsRemovableDevice(const std::string& device) {
297 string sysfs_block = SysfsBlockDevice(device);
298 string removable;
299 if (sysfs_block.empty() ||
300 !file_util::ReadFileToString(FilePath(sysfs_block).Append("removable"),
301 &removable)) {
302 return false;
303 }
304 TrimWhitespaceASCII(removable, TRIM_ALL, &removable);
305 return removable == "1";
306}
307
adlr@google.com3defe6a2009-12-04 20:57:17 +0000308std::string ErrnoNumberAsString(int err) {
309 char buf[100];
310 buf[0] = '\0';
311 return strerror_r(err, buf, sizeof(buf));
312}
313
314std::string NormalizePath(const std::string& path, bool strip_trailing_slash) {
315 string ret;
316 bool last_insert_was_slash = false;
317 for (string::const_iterator it = path.begin(); it != path.end(); ++it) {
318 if (*it == '/') {
319 if (last_insert_was_slash)
320 continue;
321 last_insert_was_slash = true;
322 } else {
323 last_insert_was_slash = false;
324 }
325 ret.push_back(*it);
326 }
327 if (strip_trailing_slash && last_insert_was_slash) {
328 string::size_type last_non_slash = ret.find_last_not_of('/');
329 if (last_non_slash != string::npos) {
330 ret.resize(last_non_slash + 1);
331 } else {
332 ret = "";
333 }
334 }
335 return ret;
336}
337
338bool FileExists(const char* path) {
339 struct stat stbuf;
340 return 0 == lstat(path, &stbuf);
341}
342
Darin Petkov30291ed2010-11-12 10:23:06 -0800343bool IsSymlink(const char* path) {
344 struct stat stbuf;
345 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
346}
347
adlr@google.com3defe6a2009-12-04 20:57:17 +0000348std::string TempFilename(string path) {
349 static const string suffix("XXXXXX");
350 CHECK(StringHasSuffix(path, suffix));
351 do {
352 string new_suffix;
353 for (unsigned int i = 0; i < suffix.size(); i++) {
354 int r = rand() % (26 * 2 + 10); // [a-zA-Z0-9]
355 if (r < 26)
356 new_suffix.append(1, 'a' + r);
357 else if (r < (26 * 2))
358 new_suffix.append(1, 'A' + r - 26);
359 else
360 new_suffix.append(1, '0' + r - (26 * 2));
361 }
362 CHECK_EQ(new_suffix.size(), suffix.size());
363 path.resize(path.size() - new_suffix.size());
364 path.append(new_suffix);
365 } while (FileExists(path.c_str()));
366 return path;
367}
368
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700369bool MakeTempFile(const std::string& filename_template,
370 std::string* filename,
371 int* fd) {
372 DCHECK(filename || fd);
373 vector<char> buf(filename_template.size() + 1);
374 memcpy(&buf[0], filename_template.data(), filename_template.size());
375 buf[filename_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700376
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700377 int mkstemp_fd = mkstemp(&buf[0]);
378 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
379 if (filename) {
380 *filename = &buf[0];
381 }
382 if (fd) {
383 *fd = mkstemp_fd;
384 } else {
385 close(mkstemp_fd);
386 }
387 return true;
388}
389
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700390bool MakeTempDirectory(const std::string& dirname_template,
391 std::string* dirname) {
392 DCHECK(dirname);
393 vector<char> buf(dirname_template.size() + 1);
394 memcpy(&buf[0], dirname_template.data(), dirname_template.size());
395 buf[dirname_template.size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700396
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700397 char* return_code = mkdtemp(&buf[0]);
398 TEST_AND_RETURN_FALSE_ERRNO(return_code != NULL);
399 *dirname = &buf[0];
400 return true;
401}
402
adlr@google.com3defe6a2009-12-04 20:57:17 +0000403bool StringHasSuffix(const std::string& str, const std::string& suffix) {
404 if (suffix.size() > str.size())
405 return false;
406 return 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
407}
408
409bool StringHasPrefix(const std::string& str, const std::string& prefix) {
410 if (prefix.size() > str.size())
411 return false;
412 return 0 == str.compare(0, prefix.size(), prefix);
413}
414
Will Drewry8f71da82010-08-30 14:07:11 -0500415const std::string BootDevice() {
416 char boot_path[PATH_MAX];
417 // Resolve the boot device path fully, including dereferencing
418 // through dm-verity.
419 int ret = rootdev(boot_path, sizeof(boot_path), true, false);
420
421 if (ret < 0) {
422 LOG(ERROR) << "rootdev failed to find the root device";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000423 return "";
424 }
Will Drewry8f71da82010-08-30 14:07:11 -0500425 LOG_IF(WARNING, ret > 0) << "rootdev found a device name with no device node";
426
427 // This local variable is used to construct the return string and is not
428 // passed around after use.
429 return boot_path;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000430}
431
Andrew de los Reyesf9185172010-05-03 11:07:05 -0700432const string BootKernelDevice(const std::string& boot_device) {
433 // Currntly this assumes the last digit of the boot device is
434 // 3, 5, or 7, and changes it to 2, 4, or 6, respectively, to
435 // get the kernel device.
436 string ret = boot_device;
437 if (ret.empty())
438 return ret;
439 char last_char = ret[ret.size() - 1];
440 if (last_char == '3' || last_char == '5' || last_char == '7') {
441 ret[ret.size() - 1] = last_char - 1;
442 return ret;
443 }
444 return "";
445}
446
adlr@google.com3defe6a2009-12-04 20:57:17 +0000447bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700448 const string& mountpoint,
449 unsigned long mountflags) {
450 int rc = mount(device.c_str(), mountpoint.c_str(), "ext3", mountflags, NULL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000451 if (rc < 0) {
452 string msg = ErrnoNumberAsString(errno);
453 LOG(ERROR) << "Unable to mount destination device: " << msg << ". "
454 << device << " on " << mountpoint;
455 return false;
456 }
457 return true;
458}
459
460bool UnmountFilesystem(const string& mountpoint) {
461 TEST_AND_RETURN_FALSE_ERRNO(umount(mountpoint.c_str()) == 0);
462 return true;
463}
464
Darin Petkovd3f8c892010-10-12 21:38:45 -0700465bool GetFilesystemSize(const std::string& device,
466 int* out_block_count,
467 int* out_block_size) {
468 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY));
469 TEST_AND_RETURN_FALSE(fd >= 0);
470 ScopedFdCloser fd_closer(&fd);
471 return GetFilesystemSizeFromFD(fd, out_block_count, out_block_size);
472}
473
474bool GetFilesystemSizeFromFD(int fd,
475 int* out_block_count,
476 int* out_block_size) {
477 TEST_AND_RETURN_FALSE(fd >= 0);
478
479 // Determine the ext3 filesystem size by directly reading the block count and
480 // block size information from the superblock. See include/linux/ext3_fs.h for
481 // more details on the structure.
482 ssize_t kBufferSize = 16 * sizeof(uint32_t);
483 char buffer[kBufferSize];
484 const int kSuperblockOffset = 1024;
485 if (HANDLE_EINTR(pread(fd, buffer, kBufferSize, kSuperblockOffset)) !=
486 kBufferSize) {
487 PLOG(ERROR) << "Unable to determine file system size:";
488 return false;
489 }
490 uint32_t block_count; // ext3_fs.h: ext3_super_block.s_blocks_count
491 uint32_t log_block_size; // ext3_fs.h: ext3_super_block.s_log_block_size
492 uint16_t magic; // ext3_fs.h: ext3_super_block.s_magic
493 memcpy(&block_count, &buffer[1 * sizeof(int32_t)], sizeof(block_count));
494 memcpy(&log_block_size, &buffer[6 * sizeof(int32_t)], sizeof(log_block_size));
495 memcpy(&magic, &buffer[14 * sizeof(int32_t)], sizeof(magic));
496 block_count = le32toh(block_count);
497 const int kExt3MinBlockLogSize = 10; // ext3_fs.h: EXT3_MIN_BLOCK_LOG_SIZE
498 log_block_size = le32toh(log_block_size) + kExt3MinBlockLogSize;
499 magic = le16toh(magic);
500
501 // Sanity check the parameters.
502 const uint16_t kExt3SuperMagic = 0xef53; // ext3_fs.h: EXT3_SUPER_MAGIC
503 TEST_AND_RETURN_FALSE(magic == kExt3SuperMagic);
504 const int kExt3MinBlockSize = 1024; // ext3_fs.h: EXT3_MIN_BLOCK_SIZE
505 const int kExt3MaxBlockSize = 4096; // ext3_fs.h: EXT3_MAX_BLOCK_SIZE
506 int block_size = 1 << log_block_size;
507 TEST_AND_RETURN_FALSE(block_size >= kExt3MinBlockSize &&
508 block_size <= kExt3MaxBlockSize);
509 TEST_AND_RETURN_FALSE(block_count > 0);
510
511 if (out_block_count) {
512 *out_block_count = block_count;
513 }
514 if (out_block_size) {
515 *out_block_size = block_size;
516 }
517 return true;
518}
519
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700520bool GetBootloader(BootLoader* out_bootloader) {
521 // For now, hardcode to syslinux.
522 *out_bootloader = BootLoader_SYSLINUX;
523 return true;
524}
525
Darin Petkova0b9e772011-10-06 05:05:56 -0700526string GetAndFreeGError(GError** error) {
527 if (!*error) {
528 return "Unknown GLib error.";
529 }
530 string message =
531 base::StringPrintf("GError(%d): %s",
532 (*error)->code,
533 (*error)->message ? (*error)->message : "(unknown)");
534 g_error_free(*error);
535 *error = NULL;
536 return message;
Andrew de los Reyesc7020782010-04-28 10:46:04 -0700537}
538
Darin Petkov296889c2010-07-23 16:20:54 -0700539bool Reboot() {
540 vector<string> command;
541 command.push_back("/sbin/shutdown");
542 command.push_back("-r");
543 command.push_back("now");
544 int rc = 0;
Darin Petkov85d02b72011-05-17 13:25:51 -0700545 Subprocess::SynchronousExec(command, &rc, NULL);
Darin Petkov296889c2010-07-23 16:20:54 -0700546 TEST_AND_RETURN_FALSE(rc == 0);
547 return true;
548}
549
Andrew de los Reyes712b3ac2011-01-07 13:47:52 -0800550namespace {
551// Do the actual trigger. We do it as a main-loop callback to (try to) get a
552// consistent stack trace.
553gboolean TriggerCrashReporterUpload(void* unused) {
554 pid_t pid = fork();
555 CHECK(pid >= 0) << "fork failed"; // fork() failed. Something is very wrong.
556 if (pid == 0) {
557 // We are the child. Crash.
558 abort(); // never returns
559 }
560 // We are the parent. Wait for child to terminate.
561 pid_t result = waitpid(pid, NULL, 0);
562 LOG_IF(ERROR, result < 0) << "waitpid() failed";
563 return FALSE; // Don't call this callback again
564}
565} // namespace {}
566
567void ScheduleCrashReporterUpload() {
568 g_idle_add(&TriggerCrashReporterUpload, NULL);
569}
570
Darin Petkovc6c135c2010-08-11 13:36:18 -0700571bool SetProcessPriority(ProcessPriority priority) {
572 int prio = static_cast<int>(priority);
573 LOG(INFO) << "Setting process priority to " << prio;
574 TEST_AND_RETURN_FALSE(setpriority(PRIO_PROCESS, 0, prio) == 0);
575 return true;
576}
577
578int ComparePriorities(ProcessPriority priority_lhs,
579 ProcessPriority priority_rhs) {
580 return static_cast<int>(priority_rhs) - static_cast<int>(priority_lhs);
581}
582
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700583int FuzzInt(int value, unsigned int range) {
584 int min = value - range / 2;
585 int max = value + range - range / 2;
586 return base::RandInt(min, max);
587}
588
Andrew de los Reyesf3ed8e72011-02-16 10:35:46 -0800589gboolean GlibRunClosure(gpointer data) {
590 google::protobuf::Closure* callback =
591 reinterpret_cast<google::protobuf::Closure*>(data);
592 callback->Run();
593 return FALSE;
594}
595
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700596string FormatSecs(unsigned secs) {
597 return FormatTimeDelta(base::TimeDelta::FromSeconds(secs));
598}
599
600string FormatTimeDelta(base::TimeDelta delta) {
601 // Canonicalize into days, hours, minutes, seconds and microseconds.
602 unsigned days = delta.InDays();
603 delta -= base::TimeDelta::FromDays(days);
604 unsigned hours = delta.InHours();
605 delta -= base::TimeDelta::FromHours(hours);
606 unsigned mins = delta.InMinutes();
607 delta -= base::TimeDelta::FromMinutes(mins);
608 unsigned secs = delta.InSeconds();
609 delta -= base::TimeDelta::FromSeconds(secs);
610 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800611
612 // Construct and return string.
613 string str;
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700614 if (days)
615 base::StringAppendF(&str, "%ud", days);
616 if (days || hours)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800617 base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700618 if (days || hours || mins)
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800619 base::StringAppendF(&str, "%um", mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700620 base::StringAppendF(&str, "%u", secs);
621 if (usecs) {
622 int width = 6;
623 while ((usecs / 10) * 10 == usecs) {
624 usecs /= 10;
625 width--;
626 }
627 base::StringAppendF(&str, ".%0*u", width, usecs);
628 }
629 base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800630 return str;
631}
632
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700633string ToString(const Time utc_time) {
634 Time::Exploded exp_time;
635 utc_time.UTCExplode(&exp_time);
636 return StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
637 exp_time.month,
638 exp_time.day_of_month,
639 exp_time.year,
640 exp_time.hour,
641 exp_time.minute,
642 exp_time.second);
643}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000644
645} // namespace utils
646
647} // namespace chromeos_update_engine