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