blob: bd33ecaf7554bf5bc2c402a3efea3efda110c834 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
adlr@google.com3defe6a2009-12-04 20:57:17 +000016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/common/utils.h"
Darin Petkovf74eb652010-08-04 12:08:38 -070018
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <dirent.h>
Alex Deymoc1711e22014-08-08 13:16:23 -070022#include <elf.h>
Alex Deymo6f20dd42015-08-18 16:42:46 -070023#include <endian.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000024#include <errno.h>
Andrew de los Reyes970bb282009-12-09 16:34:04 -080025#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000026#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070029#include <sys/mount.h>
30#include <sys/resource.h>
Kelvin Zhang8933d572021-01-28 10:17:34 -050031#include <sys/sendfile.h>
Alex Deymoc4acdf42014-05-28 21:07:10 -070032#include <sys/stat.h>
33#include <sys/types.h>
Yifan Hongc80de2d2020-02-25 17:13:53 -080034#include <time.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000035#include <unistd.h>
Darin Petkovf74eb652010-08-04 12:08:38 -070036
adlr@google.com3defe6a2009-12-04 20:57:17 +000037#include <algorithm>
Kelvin Zhang49170aa2022-11-28 10:55:16 -080038#include <filesystem>
Alex Vakulenkod2779df2014-06-16 13:19:00 -070039#include <utility>
Chris Sosac1972482013-04-30 22:31:10 -070040#include <vector>
Darin Petkovf74eb652010-08-04 12:08:38 -070041
Kokoa Matsuda11c3da62024-10-23 13:40:44 +090042#include <android-base/stringprintf.h>
Colin Cross84fe9da2021-12-21 13:19:14 -080043#include <android-base/strings.h>
Alex Vakulenko4906c1c2014-08-21 13:17:44 -070044#include <base/callback.h>
Ben Chan736fcb52014-05-21 18:28:22 -070045#include <base/files/file_path.h>
Alex Deymo192393b2014-11-10 15:58:38 -080046#include <base/files/file_util.h>
Ben Chan736fcb52014-05-21 18:28:22 -070047#include <base/files/scoped_file.h>
Alex Deymoc00c98a2015-03-17 17:38:00 -070048#include <base/format_macros.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070049#include <base/location.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040050#include <base/logging.h>
Chris Sosafc661a12013-02-26 14:43:21 -080051#include <base/posix/eintr_wrapper.h>
Will Drewry8f71da82010-08-30 14:07:11 -050052#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070053#include <base/strings/string_number_conversions.h>
54#include <base/strings/string_split.h>
Kelvin Zhang0c184242024-10-25 11:19:27 -070055#include <android-base/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070056#include <brillo/data_encoding.h>
Will Drewry8f71da82010-08-30 14:07:11 -050057
Alex Deymo39910dc2015-11-09 17:04:30 -080058#include "update_engine/common/constants.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080059#include "update_engine/common/subprocess.h"
Kelvin Zhange47767a2023-05-16 13:00:58 -070060#ifdef __ANDROID__
Kelvin Zhang32a73a92022-12-19 12:27:41 -080061#include "update_engine/common/platform_constants.h"
Kelvin Zhange47767a2023-05-16 13:00:58 -070062#endif
Alex Deymo39910dc2015-11-09 17:04:30 -080063#include "update_engine/payload_consumer/file_descriptor.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000064
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070065using base::Time;
Gilad Arnold8e3f1262013-01-08 14:59:54 -080066using base::TimeDelta;
adlr@google.com3defe6a2009-12-04 20:57:17 +000067using std::min;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070068using std::numeric_limits;
adlr@google.com3defe6a2009-12-04 20:57:17 +000069using std::string;
70using std::vector;
71
72namespace chromeos_update_engine {
73
Ben Chan77a1eba2012-10-07 22:54:55 -070074namespace {
75
76// The following constants control how UnmountFilesystem should retry if
77// umount() fails with an errno EBUSY, i.e. retry 5 times over the course of
78// one second.
79const int kUnmountMaxNumOfRetries = 5;
80const int kUnmountRetryIntervalInMicroseconds = 200 * 1000; // 200 ms
Alex Deymo032e7722014-03-25 17:53:56 -070081
82// Number of bytes to read from a file to attempt to detect its contents. Used
83// in GetFileFormat.
84const int kGetFileFormatMaxHeaderSize = 32;
85
Alex Deymodd132f32015-09-14 19:12:07 -070086// The path to the kernel's boot_id.
87const char kBootIdPath[] = "/proc/sys/kernel/random/boot_id";
88
Kelvin Zhangfab31ad2024-03-26 12:56:08 -070089} // namespace
Alex Deymo5aa1c542015-09-18 01:02:33 -070090// If |path| is absolute, or explicit relative to the current working directory,
91// leaves it as is. Otherwise, uses the system's temp directory, as defined by
92// base::GetTempDir() and prepends it to |path|. On success stores the full
93// temporary path in |template_path| and returns true.
94bool GetTempName(const string& path, base::FilePath* template_path) {
Alex Vakulenko0103c362016-01-20 07:56:15 -080095 if (path[0] == '/' ||
96 base::StartsWith(path, "./", base::CompareCase::SENSITIVE) ||
97 base::StartsWith(path, "../", base::CompareCase::SENSITIVE)) {
Alex Deymo5aa1c542015-09-18 01:02:33 -070098 *template_path = base::FilePath(path);
99 return true;
100 }
101
102 base::FilePath temp_dir;
Sen Jiang9c123462015-11-19 13:16:23 -0800103#ifdef __ANDROID__
Sen Jiangc2b37662019-01-09 16:51:18 -0800104 temp_dir = base::FilePath(constants::kNonVolatileDirectory).Append("tmp");
Alex Deymo32951022016-08-10 17:02:49 -0700105#else
Sen Jiangc2b37662019-01-09 16:51:18 -0800106 TEST_AND_RETURN_FALSE(base::GetTempDir(&temp_dir));
Alex Deymo32951022016-08-10 17:02:49 -0700107#endif // __ANDROID__
Sen Jiang9c123462015-11-19 13:16:23 -0800108 if (!base::PathExists(temp_dir))
109 TEST_AND_RETURN_FALSE(base::CreateDirectory(temp_dir));
Alex Deymo5aa1c542015-09-18 01:02:33 -0700110 *template_path = temp_dir.Append(path);
111 return true;
112}
113
adlr@google.com3defe6a2009-12-04 20:57:17 +0000114namespace utils {
115
Alex Deymo335516c2016-11-28 13:37:06 -0800116bool WriteFile(const char* path, const void* data, size_t data_len) {
117 int fd = HANDLE_EINTR(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600));
118 TEST_AND_RETURN_FALSE_ERRNO(fd >= 0);
119 ScopedFdCloser fd_closer(&fd);
120 return WriteAll(fd, data, data_len);
Andrew de los Reyes970bb282009-12-09 16:34:04 -0800121}
122
Alex Deymo0d298542016-03-30 18:31:49 -0700123bool ReadAll(
124 int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof) {
125 char* c_buf = static_cast<char*>(buf);
126 size_t bytes_read = 0;
127 *eof = false;
128 while (bytes_read < count) {
129 ssize_t rc = HANDLE_EINTR(read(fd, c_buf + bytes_read, count - bytes_read));
130 if (rc < 0) {
131 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
132 // input and we are in non-blocking mode.
133 if (errno != EWOULDBLOCK && errno != EAGAIN) {
134 PLOG(ERROR) << "Error reading fd " << fd;
135 *out_bytes_read = bytes_read;
136 return false;
137 }
138 break;
139 } else if (rc == 0) {
140 // A value of 0 means that we reached EOF and there is nothing else to
141 // read from this fd.
142 *eof = true;
143 break;
144 } else {
145 bytes_read += rc;
146 }
147 }
148 *out_bytes_read = bytes_read;
149 return true;
150}
151
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700152bool WriteAll(int fd, const void* buf, size_t count) {
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700153 const char* c_buf = static_cast<const char*>(buf);
154 ssize_t bytes_written = 0;
155 while (bytes_written < static_cast<ssize_t>(count)) {
156 ssize_t rc = write(fd, c_buf + bytes_written, count - bytes_written);
157 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
158 bytes_written += rc;
159 }
160 return true;
161}
162
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700163bool PWriteAll(int fd, const void* buf, size_t count, off_t offset) {
164 const char* c_buf = static_cast<const char*>(buf);
Gilad Arnold780db212012-07-11 13:12:49 -0700165 size_t bytes_written = 0;
166 int num_attempts = 0;
167 while (bytes_written < count) {
168 num_attempts++;
Amin Hassanib2689592019-01-13 17:04:28 -0800169 ssize_t rc = pwrite(fd,
170 c_buf + bytes_written,
171 count - bytes_written,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700172 offset + bytes_written);
Gilad Arnold780db212012-07-11 13:12:49 -0700173 // TODO(garnold) for debugging failure in chromium-os:31077; to be removed.
174 if (rc < 0) {
175 PLOG(ERROR) << "pwrite error; num_attempts=" << num_attempts
Amin Hassanib2689592019-01-13 17:04:28 -0800176 << " bytes_written=" << bytes_written << " count=" << count
177 << " offset=" << offset;
Gilad Arnold780db212012-07-11 13:12:49 -0700178 }
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700179 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
180 bytes_written += rc;
181 }
182 return true;
183}
184
Kelvin Zhang1a0ed712022-01-26 16:09:05 -0800185bool WriteAll(FileDescriptor* fd, const void* buf, size_t count) {
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800186 const char* c_buf = static_cast<const char*>(buf);
187 ssize_t bytes_written = 0;
188 while (bytes_written < static_cast<ssize_t>(count)) {
189 ssize_t rc = fd->Write(c_buf + bytes_written, count - bytes_written);
190 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
191 bytes_written += rc;
192 }
193 return true;
194}
195
Kelvin Zhang4b280242020-11-06 16:07:45 -0500196bool WriteAll(const FileDescriptorPtr& fd,
197 const void* buf,
198 size_t count,
199 off_t offset) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700200 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
201 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800202 return WriteAll(fd, buf, count);
203}
204
Amin Hassanib2689592019-01-13 17:04:28 -0800205bool PReadAll(
206 int fd, void* buf, size_t count, off_t offset, ssize_t* out_bytes_read) {
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700207 char* c_buf = static_cast<char*>(buf);
208 ssize_t bytes_read = 0;
209 while (bytes_read < static_cast<ssize_t>(count)) {
Amin Hassanib2689592019-01-13 17:04:28 -0800210 ssize_t rc =
211 pread(fd, c_buf + bytes_read, count - bytes_read, offset + bytes_read);
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700212 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
213 if (rc == 0) {
214 break;
215 }
216 bytes_read += rc;
217 }
218 *out_bytes_read = bytes_read;
219 return true;
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700220}
221
Kelvin Zhang1a0ed712022-01-26 16:09:05 -0800222bool ReadAll(FileDescriptor* fd,
Kelvin Zhang4b280242020-11-06 16:07:45 -0500223 void* buf,
224 size_t count,
225 off_t offset,
226 ssize_t* out_bytes_read) {
Allie Wood0c8cf7e2015-04-23 19:24:49 -0700227 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(offset, SEEK_SET) !=
228 static_cast<off_t>(-1));
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -0800229 char* c_buf = static_cast<char*>(buf);
230 ssize_t bytes_read = 0;
231 while (bytes_read < static_cast<ssize_t>(count)) {
232 ssize_t rc = fd->Read(c_buf + bytes_read, count - bytes_read);
233 TEST_AND_RETURN_FALSE_ERRNO(rc >= 0);
234 if (rc == 0) {
235 break;
236 }
237 bytes_read += rc;
238 }
239 *out_bytes_read = bytes_read;
240 return true;
241}
242
Kelvin Zhang1a0ed712022-01-26 16:09:05 -0800243bool PReadAll(FileDescriptor* fd,
Kelvin Zhangc3c0a3a2020-11-09 16:08:13 -0500244 void* buf,
245 size_t count,
246 off_t offset,
247 ssize_t* out_bytes_read) {
248 auto old_off = fd->Seek(0, SEEK_CUR);
249 TEST_AND_RETURN_FALSE_ERRNO(old_off >= 0);
250
251 auto success = ReadAll(fd, buf, count, offset, out_bytes_read);
252 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(old_off, SEEK_SET) == old_off);
253 return success;
254}
255
256bool PWriteAll(const FileDescriptorPtr& fd,
257 const void* buf,
258 size_t count,
259 off_t offset) {
260 auto old_off = fd->Seek(0, SEEK_CUR);
261 TEST_AND_RETURN_FALSE_ERRNO(old_off >= 0);
262
263 auto success = WriteAll(fd, buf, count, offset);
264 TEST_AND_RETURN_FALSE_ERRNO(fd->Seek(old_off, SEEK_SET) == old_off);
265 return success;
266}
267
Gilad Arnold19a45f02012-07-19 12:36:10 -0700268// Append |nbytes| of content from |buf| to the vector pointed to by either
269// |vec_p| or |str_p|.
Amin Hassanib2689592019-01-13 17:04:28 -0800270static void AppendBytes(const uint8_t* buf,
271 size_t nbytes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700272 brillo::Blob* vec_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700273 CHECK(buf);
274 CHECK(vec_p);
275 vec_p->insert(vec_p->end(), buf, buf + nbytes);
276}
Amin Hassanib2689592019-01-13 17:04:28 -0800277static void AppendBytes(const uint8_t* buf, size_t nbytes, string* str_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700278 CHECK(buf);
279 CHECK(str_p);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800280 str_p->append(buf, buf + nbytes);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700281}
282
283// Reads from an open file |fp|, appending the read content to the container
284// pointer to by |out_p|. Returns true upon successful reading all of the
Darin Petkov8e447e02013-04-16 16:23:50 +0200285// file's content, false otherwise. If |size| is not -1, reads up to |size|
286// bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700287template <class T>
Darin Petkov8e447e02013-04-16 16:23:50 +0200288static bool Read(FILE* fp, off_t size, T* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700289 CHECK(fp);
Darin Petkov8e447e02013-04-16 16:23:50 +0200290 CHECK(size == -1 || size >= 0);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800291 uint8_t buf[1024];
Darin Petkov8e447e02013-04-16 16:23:50 +0200292 while (size == -1 || size > 0) {
293 off_t bytes_to_read = sizeof(buf);
294 if (size > 0 && bytes_to_read > size) {
295 bytes_to_read = size;
296 }
297 size_t nbytes = fread(buf, 1, bytes_to_read, fp);
298 if (!nbytes) {
299 break;
300 }
Gilad Arnold19a45f02012-07-19 12:36:10 -0700301 AppendBytes(buf, nbytes, out_p);
Darin Petkov8e447e02013-04-16 16:23:50 +0200302 if (size != -1) {
303 CHECK(size >= static_cast<off_t>(nbytes));
304 size -= nbytes;
305 }
306 }
307 if (ferror(fp)) {
308 return false;
309 }
310 return size == 0 || feof(fp);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700311}
312
Darin Petkov8e447e02013-04-16 16:23:50 +0200313// Opens a file |path| for reading and appends its the contents to a container
314// |out_p|. Starts reading the file from |offset|. If |offset| is beyond the end
315// of the file, returns success. If |size| is not -1, reads up to |size| bytes.
Gilad Arnold19a45f02012-07-19 12:36:10 -0700316template <class T>
Alex Deymof329b932014-10-30 01:37:48 -0700317static bool ReadFileChunkAndAppend(const string& path,
Darin Petkov8e447e02013-04-16 16:23:50 +0200318 off_t offset,
319 off_t size,
320 T* out_p) {
321 CHECK_GE(offset, 0);
322 CHECK(size == -1 || size >= 0);
Ben Chan736fcb52014-05-21 18:28:22 -0700323 base::ScopedFILE fp(fopen(path.c_str(), "r"));
Darin Petkov8e447e02013-04-16 16:23:50 +0200324 if (!fp.get())
adlr@google.com3defe6a2009-12-04 20:57:17 +0000325 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200326 if (offset) {
327 // Return success without appending any data if a chunk beyond the end of
328 // the file is requested.
329 if (offset >= FileSize(path)) {
330 return true;
331 }
332 TEST_AND_RETURN_FALSE_ERRNO(fseek(fp.get(), offset, SEEK_SET) == 0);
333 }
334 return Read(fp.get(), size, out_p);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000335}
336
Alex Deymo10875d92014-11-10 21:52:57 -0800337// TODO(deymo): This is only used in unittest, but requires the private
338// Read<string>() defined here. Expose Read<string>() or move to base/ version.
339bool ReadPipe(const string& cmd, string* out_p) {
Gilad Arnold19a45f02012-07-19 12:36:10 -0700340 FILE* fp = popen(cmd.c_str(), "r");
341 if (!fp)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000342 return false;
Darin Petkov8e447e02013-04-16 16:23:50 +0200343 bool success = Read(fp, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700344 return (success && pclose(fp) >= 0);
345}
346
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700347bool ReadFile(const string& path, brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200348 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700349}
350
Darin Petkov8e447e02013-04-16 16:23:50 +0200351bool ReadFile(const string& path, string* out_p) {
352 return ReadFileChunkAndAppend(path, 0, -1, out_p);
Gilad Arnold19a45f02012-07-19 12:36:10 -0700353}
354
Amin Hassanib2689592019-01-13 17:04:28 -0800355bool ReadFileChunk(const string& path,
356 off_t offset,
357 off_t size,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700358 brillo::Blob* out_p) {
Darin Petkov8e447e02013-04-16 16:23:50 +0200359 return ReadFileChunkAndAppend(path, offset, size, out_p);
360}
361
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700362off_t BlockDevSize(int fd) {
Daniel Zheng3e881aa2022-09-07 22:10:29 +0000363 uint64_t dev_size{};
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700364 int rc = ioctl(fd, BLKGETSIZE64, &dev_size);
365 if (rc == -1) {
366 dev_size = -1;
367 PLOG(ERROR) << "Error running ioctl(BLKGETSIZE64) on " << fd;
368 }
369 return dev_size;
370}
371
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700372off_t FileSize(int fd) {
Kelvin Zhang0c184242024-10-25 11:19:27 -0700373 struct stat stbuf {};
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700374 int rc = fstat(fd, &stbuf);
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700375 CHECK_EQ(rc, 0);
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700376 if (rc < 0) {
377 PLOG(ERROR) << "Error stat-ing " << fd;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700378 return rc;
Gabe Blackb92cd2e2014-09-08 02:47:41 -0700379 }
380 if (S_ISREG(stbuf.st_mode))
381 return stbuf.st_size;
382 if (S_ISBLK(stbuf.st_mode))
383 return BlockDevSize(fd);
384 LOG(ERROR) << "Couldn't determine the type of " << fd;
385 return -1;
386}
387
388off_t FileSize(const string& path) {
389 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
390 if (fd == -1) {
391 PLOG(ERROR) << "Error opening " << path;
392 return fd;
393 }
394 off_t size = FileSize(fd);
395 if (size == -1)
396 PLOG(ERROR) << "Error getting file size of " << path;
397 close(fd);
398 return size;
Andrew de los Reyesf4c7ef12010-04-30 10:37:00 -0700399}
400
Kelvin Zhang02fe6622021-11-01 16:37:58 -0700401bool SendFile(int out_fd, int in_fd, size_t count) {
402 off64_t offset = lseek(in_fd, 0, SEEK_CUR);
403 TEST_AND_RETURN_FALSE_ERRNO(offset >= 0);
404 constexpr size_t BUFFER_SIZE = 4096;
405 while (count > 0) {
406 const auto bytes_written =
407 sendfile(out_fd, in_fd, &offset, std::min(count, BUFFER_SIZE));
408 TEST_AND_RETURN_FALSE_ERRNO(bytes_written > 0);
409 count -= bytes_written;
410 }
411 return true;
412}
413
Kelvin Zhangc80d39b2023-10-25 09:30:16 -0700414bool DeleteDirectory(const char* dirname) {
Daniel Zheng6a00fe92024-04-09 14:44:21 -0700415 if (!std::filesystem::exists(dirname)) {
416 return true;
417 }
Kelvin Zhangc80d39b2023-10-25 09:30:16 -0700418 const std::string tmpdir = std::string(dirname) + "_deleted";
419 std::filesystem::remove_all(tmpdir);
420 if (rename(dirname, tmpdir.c_str()) != 0) {
421 PLOG(ERROR) << "Failed to rename " << dirname << " to " << tmpdir;
422 return false;
423 }
424 std::filesystem::remove_all(tmpdir);
425 return true;
426}
427
Daniel Zhengbcc64c42024-04-23 10:32:53 -0700428bool FsyncDirectoryContents(const char* dirname) {
429 std::filesystem::path dir_path(dirname);
430
431 std::error_code ec;
432 if (!std::filesystem::exists(dir_path, ec) ||
433 !std::filesystem::is_directory(dir_path, ec)) {
434 LOG(ERROR) << "Error: Invalid directory path: " << dirname << std::endl;
435 return false;
436 }
437
438 for (const auto& entry : std::filesystem::directory_iterator(dirname, ec)) {
439 if (entry.is_regular_file()) {
440 int fd = open(entry.path().c_str(), O_RDONLY | O_CLOEXEC);
441 if (fd == -1) {
442 LOG(ERROR) << "open failed: " << entry.path();
443 return false;
444 }
445
446 if (fsync(fd) == -1) {
447 LOG(ERROR) << "fsync failed";
448 return false;
449 }
450
451 close(fd);
452 }
453 }
454
455 return true;
456}
457
Kelvin Zhang49170aa2022-11-28 10:55:16 -0800458bool FsyncDirectory(const char* dirname) {
Daniel Zhengbcc64c42024-04-23 10:32:53 -0700459 if (!FsyncDirectoryContents(dirname)) {
460 LOG(ERROR) << "failed to fsync directory contents";
461 return false;
462 }
Kelvin Zhang49170aa2022-11-28 10:55:16 -0800463 android::base::unique_fd fd(
464 TEMP_FAILURE_RETRY(open(dirname, O_RDONLY | O_CLOEXEC)));
465 if (fd == -1) {
466 PLOG(ERROR) << "Failed to open " << dirname;
467 return false;
468 }
469 if (fsync(fd) == -1) {
470 if (errno == EROFS || errno == EINVAL) {
471 PLOG(WARNING) << "Skip fsync " << dirname
472 << " on a file system does not support synchronization";
473 } else {
474 PLOG(ERROR) << "Failed to fsync " << dirname;
475 return false;
476 }
477 }
478 return true;
479}
480
481bool WriteStringToFileAtomic(const std::string& path,
482 std::string_view content) {
483 const std::string tmp_path = path + ".tmp";
484 {
485 const int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC;
486 android::base::unique_fd fd(
487 TEMP_FAILURE_RETRY(open(tmp_path.c_str(), flags, 0644)));
488 if (fd == -1) {
489 PLOG(ERROR) << "Failed to open " << path;
490 return false;
491 }
492 if (!WriteAll(fd.get(), content.data(), content.size())) {
493 PLOG(ERROR) << "Failed to write to fd " << fd;
494 return false;
495 }
496 // rename() without fsync() is not safe. Data could still be living on page
497 // cache. To ensure atomiticity, call fsync()
498 if (fsync(fd) != 0) {
499 PLOG(ERROR) << "Failed to fsync " << tmp_path;
500 }
501 }
502 if (rename(tmp_path.c_str(), path.c_str()) == -1) {
503 PLOG(ERROR) << "rename failed from " << tmp_path << " to " << path;
504 return false;
505 }
506 return FsyncDirectory(std::filesystem::path(path).parent_path().c_str());
507}
508
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800509void HexDumpArray(const uint8_t* const arr, const size_t length) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000510 LOG(INFO) << "Logging array of length: " << length;
511 const unsigned int bytes_per_line = 16;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700512 for (uint32_t i = 0; i < length; i += bytes_per_line) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000513 const unsigned int bytes_remaining = length - i;
Amin Hassanib2689592019-01-13 17:04:28 -0800514 const unsigned int bytes_per_this_line =
515 min(bytes_per_line, bytes_remaining);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000516 char header[100];
517 int r = snprintf(header, sizeof(header), "0x%08x : ", i);
518 TEST_AND_RETURN(r == 13);
519 string line = header;
520 for (unsigned int j = 0; j < bytes_per_this_line; j++) {
521 char buf[20];
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800522 uint8_t c = arr[i + j];
adlr@google.com3defe6a2009-12-04 20:57:17 +0000523 r = snprintf(buf, sizeof(buf), "%02x ", static_cast<unsigned int>(c));
524 TEST_AND_RETURN(r == 3);
525 line += buf;
526 }
527 LOG(INFO) << line;
528 }
529}
530
Alex Deymof329b932014-10-30 01:37:48 -0700531bool SplitPartitionName(const string& partition_name,
532 string* out_disk_name,
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800533 int* out_partition_num) {
Amin Hassanib2689592019-01-13 17:04:28 -0800534 if (!base::StartsWith(
535 partition_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800536 LOG(ERROR) << "Invalid partition device name: " << partition_name;
537 return false;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700538 }
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800539
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700540 size_t last_nondigit_pos = partition_name.find_last_not_of("0123456789");
541 if (last_nondigit_pos == string::npos ||
542 (last_nondigit_pos + 1) == partition_name.size()) {
543 LOG(ERROR) << "Unable to parse partition device name: " << partition_name;
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800544 return false;
545 }
546
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800547 if (out_disk_name) {
548 // Special case for MMC devices which have the following naming scheme:
549 // mmcblk0p2
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700550 size_t disk_name_len = last_nondigit_pos;
Amin Hassanib2689592019-01-13 17:04:28 -0800551 if (partition_name[last_nondigit_pos] != 'p' || last_nondigit_pos == 0 ||
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700552 !isdigit(partition_name[last_nondigit_pos - 1])) {
553 disk_name_len++;
554 }
555 *out_disk_name = partition_name.substr(0, disk_name_len);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800556 }
557
558 if (out_partition_num) {
Brian Norris7b428f52019-06-26 10:03:35 -0700559 string partition_str = partition_name.substr(last_nondigit_pos + 1);
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800560 *out_partition_num = atoi(partition_str.c_str());
561 }
562 return true;
563}
564
Alex Deymof329b932014-10-30 01:37:48 -0700565string MakePartitionName(const string& disk_name, int partition_num) {
Nam T. Nguyena78b28c2015-03-06 22:30:12 -0800566 if (partition_num < 1) {
567 LOG(ERROR) << "Invalid partition number: " << partition_num;
568 return string();
569 }
570
Alex Vakulenko0103c362016-01-20 07:56:15 -0800571 if (!base::StartsWith(disk_name, "/dev/", base::CompareCase::SENSITIVE)) {
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800572 LOG(ERROR) << "Invalid disk name: " << disk_name;
Alex Deymof329b932014-10-30 01:37:48 -0700573 return string();
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800574 }
575
Alex Deymof329b932014-10-30 01:37:48 -0700576 string partition_name = disk_name;
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700577 if (isdigit(partition_name.back())) {
578 // Special case for devices with names ending with a digit.
579 // Add "p" to separate the disk name from partition number,
580 // e.g. "/dev/loop0p2"
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800581 partition_name += 'p';
582 }
583
Alex Vakulenkof3f85bb2014-03-26 16:36:35 -0700584 partition_name += std::to_string(partition_num);
585
Alex Vakulenko4f5b1442014-02-21 12:19:44 -0800586 return partition_name;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700587}
588
adlr@google.com3defe6a2009-12-04 20:57:17 +0000589bool FileExists(const char* path) {
Kelvin Zhang0c184242024-10-25 11:19:27 -0700590 struct stat stbuf {};
adlr@google.com3defe6a2009-12-04 20:57:17 +0000591 return 0 == lstat(path, &stbuf);
592}
593
Darin Petkov30291ed2010-11-12 10:23:06 -0800594bool IsSymlink(const char* path) {
Kelvin Zhang0c184242024-10-25 11:19:27 -0700595 struct stat stbuf {};
Darin Petkov30291ed2010-11-12 10:23:06 -0800596 return lstat(path, &stbuf) == 0 && S_ISLNK(stbuf.st_mode) != 0;
597}
598
Kelvin Zhangdeb34452021-01-21 11:54:36 -0500599bool IsRegFile(const char* path) {
Kelvin Zhang0c184242024-10-25 11:19:27 -0700600 struct stat stbuf {};
Kelvin Zhangdeb34452021-01-21 11:54:36 -0500601 return lstat(path, &stbuf) == 0 && S_ISREG(stbuf.st_mode) != 0;
602}
603
Alex Deymof329b932014-10-30 01:37:48 -0700604bool MakeTempFile(const string& base_filename_template,
605 string* filename,
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700606 int* fd) {
Alex Deymo5aa1c542015-09-18 01:02:33 -0700607 base::FilePath filename_template;
608 TEST_AND_RETURN_FALSE(
609 GetTempName(base_filename_template, &filename_template));
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700610 DCHECK(filename || fd);
Alex Deymo5aa1c542015-09-18 01:02:33 -0700611 vector<char> buf(filename_template.value().size() + 1);
Amin Hassanib2689592019-01-13 17:04:28 -0800612 memcpy(buf.data(),
613 filename_template.value().data(),
Alex Deymo5aa1c542015-09-18 01:02:33 -0700614 filename_template.value().size());
615 buf[filename_template.value().size()] = '\0';
Darin Petkov296889c2010-07-23 16:20:54 -0700616
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800617 int mkstemp_fd = mkstemp(buf.data());
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700618 TEST_AND_RETURN_FALSE_ERRNO(mkstemp_fd >= 0);
619 if (filename) {
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800620 *filename = buf.data();
Andrew de los Reyesb10320d2010-03-31 16:44:44 -0700621 }
622 if (fd) {
623 *fd = mkstemp_fd;
624 } else {
625 close(mkstemp_fd);
626 }
627 return true;
628}
629
Alex Deymo5fb356c2016-03-25 18:48:22 -0700630bool SetBlockDeviceReadOnly(const string& device, bool read_only) {
631 int fd = HANDLE_EINTR(open(device.c_str(), O_RDONLY | O_CLOEXEC));
632 if (fd < 0) {
633 PLOG(ERROR) << "Opening block device " << device;
634 return false;
635 }
636 ScopedFdCloser fd_closer(&fd);
637 // We take no action if not needed.
Daniel Zheng3e881aa2022-09-07 22:10:29 +0000638 int read_only_flag{};
Alex Deymo5fb356c2016-03-25 18:48:22 -0700639 int expected_flag = read_only ? 1 : 0;
640 int rc = ioctl(fd, BLKROGET, &read_only_flag);
641 // In case of failure reading the setting we will try to set it anyway.
642 if (rc == 0 && read_only_flag == expected_flag)
643 return true;
644
645 rc = ioctl(fd, BLKROSET, &expected_flag);
646 if (rc != 0) {
Amin Hassanib2689592019-01-13 17:04:28 -0800647 PLOG(ERROR) << "Marking block device " << device
648 << " as read_only=" << expected_flag;
Alex Deymo5fb356c2016-03-25 18:48:22 -0700649 return false;
650 }
lin.guifc20b672023-09-01 20:01:35 +0800651
652 /*
653 * Read back the value to check if it is configured successfully.
654 * If fail, use the second method, set the file
655 * /sys/block/<partition_name>/force_ro
656 * to config the read only property.
657 */
658 rc = ioctl(fd, BLKROGET, &read_only_flag);
659 if (rc != 0) {
Daniel Zheng6a00fe92024-04-09 14:44:21 -0700660 PLOG(ERROR) << "Failed to read back block device read-only value:"
661 << device;
lin.guifc20b672023-09-01 20:01:35 +0800662 return false;
663 }
664 if (read_only_flag == expected_flag) {
665 return true;
666 }
667
668 std::array<char, PATH_MAX> device_name;
Daniel Zheng6a00fe92024-04-09 14:44:21 -0700669 char* pdevice = realpath(device.c_str(), device_name.data());
lin.guifc20b672023-09-01 20:01:35 +0800670 TEST_AND_RETURN_FALSE_ERRNO(pdevice);
671
672 std::string real_path(pdevice);
673 std::size_t offset = real_path.find_last_of('/');
Daniel Zheng6a00fe92024-04-09 14:44:21 -0700674 if (offset == std::string::npos) {
lin.guifc20b672023-09-01 20:01:35 +0800675 LOG(ERROR) << "Could not find partition name from " << real_path;
676 return false;
677 }
678 const std::string partition_name = real_path.substr(offset + 1);
679
680 std::string force_ro_file = "/sys/block/" + partition_name + "/force_ro";
Daniel Zheng6a00fe92024-04-09 14:44:21 -0700681 android::base::unique_fd fd_force_ro{
682 HANDLE_EINTR(open(force_ro_file.c_str(), O_WRONLY | O_CLOEXEC))};
lin.guifc20b672023-09-01 20:01:35 +0800683 TEST_AND_RETURN_FALSE_ERRNO(fd_force_ro >= 0);
684
685 rc = write(fd_force_ro, expected_flag ? "1" : "0", 1);
686 TEST_AND_RETURN_FALSE_ERRNO(rc > 0);
687
688 // Read back again
689 rc = ioctl(fd, BLKROGET, &read_only_flag);
690 if (rc != 0) {
Daniel Zheng6a00fe92024-04-09 14:44:21 -0700691 PLOG(ERROR) << "Failed to read back block device read-only value:"
692 << device;
lin.guifc20b672023-09-01 20:01:35 +0800693 return false;
694 }
695 if (read_only_flag != expected_flag) {
696 LOG(ERROR) << "After modifying force_ro, marking block device " << device
Daniel Zheng6a00fe92024-04-09 14:44:21 -0700697 << " as read_only=" << expected_flag;
lin.guifc20b672023-09-01 20:01:35 +0800698 return false;
699 }
Alex Deymo5fb356c2016-03-25 18:48:22 -0700700 return true;
701}
702
adlr@google.com3defe6a2009-12-04 20:57:17 +0000703bool MountFilesystem(const string& device,
Andrew de los Reyes09e56d62010-04-23 13:45:53 -0700704 const string& mountpoint,
Alex Deymo390efed2016-02-18 11:00:40 -0800705 unsigned long mountflags, // NOLINT(runtime/int)
Alex Deymo14dbd332016-03-01 18:55:54 -0800706 const string& type,
707 const string& fs_mount_options) {
Alex Deymo390efed2016-02-18 11:00:40 -0800708 vector<const char*> fstypes;
709 if (type.empty()) {
Kelvin Zhang4eae81e2021-12-09 17:07:17 -0800710 fstypes = {"ext2", "ext3", "ext4", "squashfs", "erofs"};
Alex Deymo390efed2016-02-18 11:00:40 -0800711 } else {
712 fstypes = {type.c_str()};
713 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800714 for (const char* fstype : fstypes) {
Amin Hassanib2689592019-01-13 17:04:28 -0800715 int rc = mount(device.c_str(),
716 mountpoint.c_str(),
717 fstype,
718 mountflags,
Alex Deymo14dbd332016-03-01 18:55:54 -0800719 fs_mount_options.c_str());
Alex Deymo4c82df32014-11-10 22:25:57 -0800720 if (rc == 0)
721 return true;
722
Amin Hassanib2689592019-01-13 17:04:28 -0800723 PLOG(WARNING) << "Unable to mount destination device " << device << " on "
724 << mountpoint << " as " << fstype;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000725 }
Alex Deymo390efed2016-02-18 11:00:40 -0800726 if (!type.empty()) {
727 LOG(ERROR) << "Unable to mount " << device << " with any supported type";
728 }
Alex Deymo4c82df32014-11-10 22:25:57 -0800729 return false;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000730}
731
732bool UnmountFilesystem(const string& mountpoint) {
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700733 int num_retries = 1;
734 for (;; ++num_retries) {
Ben Chan77a1eba2012-10-07 22:54:55 -0700735 if (umount(mountpoint.c_str()) == 0)
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700736 return true;
737 if (errno != EBUSY || num_retries >= kUnmountMaxNumOfRetries)
Ben Chan77a1eba2012-10-07 22:54:55 -0700738 break;
Alex Deymo8d2bbe32015-06-23 16:28:59 -0700739 usleep(kUnmountRetryIntervalInMicroseconds);
Ben Chan77a1eba2012-10-07 22:54:55 -0700740 }
Alex Deymo5ba93ad2016-08-22 19:51:59 -0700741 if (errno == EINVAL) {
742 LOG(INFO) << "Not a mountpoint: " << mountpoint;
743 return false;
744 }
745 PLOG(WARNING) << "Error unmounting " << mountpoint << " after " << num_retries
746 << " attempts. Lazy unmounting instead, error was";
747 if (umount2(mountpoint.c_str(), MNT_DETACH) != 0) {
748 PLOG(ERROR) << "Lazy unmount failed";
749 return false;
750 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000751 return true;
752}
753
Alex Deymof4116502017-03-22 17:00:31 -0700754bool IsMountpoint(const std::string& mountpoint) {
Kelvin Zhang0c184242024-10-25 11:19:27 -0700755 struct stat stdir {
756 }, stparent{};
Alex Deymof4116502017-03-22 17:00:31 -0700757
758 // Check whether the passed mountpoint is a directory and the /.. is in the
759 // same device or not. If mountpoint/.. is in a different device it means that
760 // there is a filesystem mounted there. If it is not, but they both point to
761 // the same inode it basically is the special case of /.. pointing to /. This
762 // test doesn't play well with bind mount but that's out of the scope of what
763 // we want to detect here.
764 if (lstat(mountpoint.c_str(), &stdir) != 0) {
765 PLOG(ERROR) << "Error stat'ing " << mountpoint;
766 return false;
767 }
768 if (!S_ISDIR(stdir.st_mode))
769 return false;
770
771 base::FilePath parent(mountpoint);
772 parent = parent.Append("..");
773 if (lstat(parent.value().c_str(), &stparent) != 0) {
774 PLOG(ERROR) << "Error stat'ing " << parent.value();
775 return false;
776 }
777 return S_ISDIR(stparent.st_mode) &&
778 (stparent.st_dev != stdir.st_dev || stparent.st_ino == stdir.st_ino);
779}
780
Alex Deymo032e7722014-03-25 17:53:56 -0700781// Tries to parse the header of an ELF file to obtain a human-readable
782// description of it on the |output| string.
Amin Hassanib2689592019-01-13 17:04:28 -0800783static bool GetFileFormatELF(const uint8_t* buffer,
784 size_t size,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800785 string* output) {
Alex Deymo032e7722014-03-25 17:53:56 -0700786 // 0x00: EI_MAG - ELF magic header, 4 bytes.
Alex Deymoc1711e22014-08-08 13:16:23 -0700787 if (size < SELFMAG || memcmp(buffer, ELFMAG, SELFMAG) != 0)
Alex Deymo032e7722014-03-25 17:53:56 -0700788 return false;
789 *output = "ELF";
790
791 // 0x04: EI_CLASS, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700792 if (size < EI_CLASS + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700793 return true;
Alex Deymoc1711e22014-08-08 13:16:23 -0700794 switch (buffer[EI_CLASS]) {
795 case ELFCLASS32:
Alex Deymo032e7722014-03-25 17:53:56 -0700796 *output += " 32-bit";
797 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700798 case ELFCLASS64:
Alex Deymo032e7722014-03-25 17:53:56 -0700799 *output += " 64-bit";
800 break;
801 default:
802 *output += " ?-bit";
803 }
804
805 // 0x05: EI_DATA, endianness, 1 byte.
Alex Deymoc1711e22014-08-08 13:16:23 -0700806 if (size < EI_DATA + 1)
Alex Deymo032e7722014-03-25 17:53:56 -0700807 return true;
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800808 uint8_t ei_data = buffer[EI_DATA];
Alex Deymo032e7722014-03-25 17:53:56 -0700809 switch (ei_data) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700810 case ELFDATA2LSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700811 *output += " little-endian";
812 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700813 case ELFDATA2MSB:
Alex Deymo032e7722014-03-25 17:53:56 -0700814 *output += " big-endian";
815 break;
816 default:
817 *output += " ?-endian";
818 // Don't parse anything after the 0x10 offset if endianness is unknown.
819 return true;
820 }
821
Alex Deymoc1711e22014-08-08 13:16:23 -0700822 const Elf32_Ehdr* hdr = reinterpret_cast<const Elf32_Ehdr*>(buffer);
823 // 0x12: e_machine, 2 byte endianness based on ei_data. The position (0x12)
824 // and size is the same for both 32 and 64 bits.
825 if (size < offsetof(Elf32_Ehdr, e_machine) + sizeof(hdr->e_machine))
Alex Deymo032e7722014-03-25 17:53:56 -0700826 return true;
Daniel Zheng3e881aa2022-09-07 22:10:29 +0000827 uint16_t e_machine{};
Sen Jiang771f6482018-04-04 17:59:10 -0700828 // Fix endianness regardless of the host endianness.
Alex Deymoc1711e22014-08-08 13:16:23 -0700829 if (ei_data == ELFDATA2LSB)
830 e_machine = le16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700831 else
Alex Deymoc1711e22014-08-08 13:16:23 -0700832 e_machine = be16toh(hdr->e_machine);
Alex Deymo032e7722014-03-25 17:53:56 -0700833
834 switch (e_machine) {
Alex Deymoc1711e22014-08-08 13:16:23 -0700835 case EM_386:
Alex Deymo032e7722014-03-25 17:53:56 -0700836 *output += " x86";
837 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700838 case EM_MIPS:
839 *output += " mips";
840 break;
841 case EM_ARM:
Alex Deymo032e7722014-03-25 17:53:56 -0700842 *output += " arm";
843 break;
Alex Deymoc1711e22014-08-08 13:16:23 -0700844 case EM_X86_64:
Alex Deymo032e7722014-03-25 17:53:56 -0700845 *output += " x86-64";
846 break;
847 default:
848 *output += " unknown-arch";
849 }
850 return true;
851}
852
853string GetFileFormat(const string& path) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700854 brillo::Blob buffer;
Alex Deymo032e7722014-03-25 17:53:56 -0700855 if (!ReadFileChunkAndAppend(path, 0, kGetFileFormatMaxHeaderSize, &buffer))
856 return "File not found.";
857
858 string result;
859 if (GetFileFormatELF(buffer.data(), buffer.size(), &result))
860 return result;
861
862 return "data";
863}
864
Darin Petkov5c0a8af2010-08-24 13:39:13 -0700865int FuzzInt(int value, unsigned int range) {
866 int min = value - range / 2;
867 int max = value + range - range / 2;
868 return base::RandInt(min, max);
869}
870
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700871string FormatSecs(unsigned secs) {
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800872 return FormatTimeDelta(TimeDelta::FromSeconds(secs));
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700873}
874
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800875string FormatTimeDelta(TimeDelta delta) {
David Zeuthen973449e2014-08-18 16:18:23 -0400876 string str;
877
878 // Handle negative durations by prefixing with a minus.
879 if (delta.ToInternalValue() < 0) {
880 delta *= -1;
881 str = "-";
882 }
883
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700884 // Canonicalize into days, hours, minutes, seconds and microseconds.
885 unsigned days = delta.InDays();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800886 delta -= TimeDelta::FromDays(days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700887 unsigned hours = delta.InHours();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800888 delta -= TimeDelta::FromHours(hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700889 unsigned mins = delta.InMinutes();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800890 delta -= TimeDelta::FromMinutes(mins);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700891 unsigned secs = delta.InSeconds();
Gilad Arnold8e3f1262013-01-08 14:59:54 -0800892 delta -= TimeDelta::FromSeconds(secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700893 unsigned usecs = delta.InMicroseconds();
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800894
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700895 if (days)
Kokoa Matsuda11c3da62024-10-23 13:40:44 +0900896 android::base::StringAppendF(&str, "%ud", days);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700897 if (days || hours)
Kokoa Matsuda11c3da62024-10-23 13:40:44 +0900898 android::base::StringAppendF(&str, "%uh", hours);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700899 if (days || hours || mins)
Kokoa Matsuda11c3da62024-10-23 13:40:44 +0900900 android::base::StringAppendF(&str, "%um", mins);
901 android::base::StringAppendF(&str, "%u", secs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700902 if (usecs) {
903 int width = 6;
904 while ((usecs / 10) * 10 == usecs) {
905 usecs /= 10;
906 width--;
907 }
Kokoa Matsuda11c3da62024-10-23 13:40:44 +0900908 android::base::StringAppendF(&str, ".%0*u", width, usecs);
Gilad Arnoldd7b513d2012-05-10 14:25:27 -0700909 }
Kokoa Matsuda11c3da62024-10-23 13:40:44 +0900910 android::base::StringAppendF(&str, "s");
Gilad Arnold1ebd8132012-03-05 10:19:29 -0800911 return str;
912}
913
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700914string ToString(const Time utc_time) {
Daniel Zheng3e881aa2022-09-07 22:10:29 +0000915 Time::Exploded exp_time{};
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700916 utc_time.UTCExplode(&exp_time);
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -0700917 return android::base::StringPrintf("%d/%d/%d %d:%02d:%02d GMT",
918 exp_time.month,
919 exp_time.day_of_month,
920 exp_time.year,
921 exp_time.hour,
922 exp_time.minute,
923 exp_time.second);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700924}
adlr@google.com3defe6a2009-12-04 20:57:17 +0000925
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700926string ToString(bool b) {
927 return (b ? "true" : "false");
928}
929
Alex Deymo1c656c42013-06-28 11:02:14 -0700930string ToString(DownloadSource source) {
Jay Srinivasan19409b72013-04-12 19:23:36 -0700931 switch (source) {
Amin Hassanib2689592019-01-13 17:04:28 -0800932 case kDownloadSourceHttpsServer:
933 return "HttpsServer";
934 case kDownloadSourceHttpServer:
935 return "HttpServer";
936 case kDownloadSourceHttpPeer:
937 return "HttpPeer";
938 case kNumDownloadSources:
939 return "Unknown";
940 // Don't add a default case to let the compiler warn about newly added
941 // download sources which should be added here.
Jay Srinivasan19409b72013-04-12 19:23:36 -0700942 }
943
944 return "Unknown";
945}
946
Alex Deymo1c656c42013-06-28 11:02:14 -0700947string ToString(PayloadType payload_type) {
948 switch (payload_type) {
Amin Hassanib2689592019-01-13 17:04:28 -0800949 case kPayloadTypeDelta:
950 return "Delta";
951 case kPayloadTypeFull:
952 return "Full";
953 case kPayloadTypeForcedFull:
954 return "ForcedFull";
955 case kNumPayloadTypes:
956 return "Unknown";
957 // Don't add a default case to let the compiler warn about newly added
958 // payload types which should be added here.
Alex Deymo1c656c42013-06-28 11:02:14 -0700959 }
960
961 return "Unknown";
962}
963
David Zeuthena99981f2013-04-29 13:42:47 -0700964ErrorCode GetBaseErrorCode(ErrorCode code) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700965 // Ignore the higher order bits in the code by applying the mask as
966 // we want the enumerations to be in the small contiguous range
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700967 // with values less than ErrorCode::kUmaReportedMax.
968 ErrorCode base_code = static_cast<ErrorCode>(
969 static_cast<int>(code) & ~static_cast<int>(ErrorCode::kSpecialFlags));
Jay Srinivasanf0572052012-10-23 18:12:56 -0700970
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800971 // Make additional adjustments required for UMA and error classification.
972 // TODO(jaysri): Move this logic to UeErrorCode.cc when we fix
973 // chromium-os:34369.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700974 if (base_code >= ErrorCode::kOmahaRequestHTTPResponseBase) {
Jay Srinivasanf0572052012-10-23 18:12:56 -0700975 // Since we want to keep the enums to a small value, aggregate all HTTP
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800976 // errors into this one bucket for UMA and error classification purposes.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800977 LOG(INFO) << "Converting error code " << base_code
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700978 << " to ErrorCode::kOmahaErrorInHTTPResponse";
979 base_code = ErrorCode::kOmahaErrorInHTTPResponse;
Jay Srinivasanf0572052012-10-23 18:12:56 -0700980 }
981
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800982 return base_code;
983}
984
Kelvin Zhangd7191032020-08-11 10:48:16 -0400985string StringVectorToString(const vector<string>& vec_str) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700986 string str = "[";
Amin Hassanib2689592019-01-13 17:04:28 -0800987 for (vector<string>::const_iterator i = vec_str.begin(); i != vec_str.end();
988 ++i) {
Alex Deymof329b932014-10-30 01:37:48 -0700989 if (i != vec_str.begin())
David Zeuthen27a48bc2013-08-06 12:06:29 -0700990 str += ", ";
991 str += '"';
992 str += *i;
993 str += '"';
994 }
995 str += "]";
996 return str;
997}
998
Sen Jiang2703ef42017-03-16 13:36:21 -0700999// The P2P file id should be the same for devices running new version and old
1000// version so that they can share it with each other. The hash in the response
1001// was base64 encoded, but now that we switched to use "hash_sha256" field which
1002// is hex encoded, we have to convert them back to base64 for P2P. However, the
1003// base64 encoded hash was base64 encoded here again historically for some
1004// reason, so we keep the same behavior here.
1005string CalculateP2PFileId(const brillo::Blob& payload_hash,
1006 size_t payload_size) {
1007 string encoded_hash = brillo::data_encoding::Base64Encode(
1008 brillo::data_encoding::Base64Encode(payload_hash));
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -07001009 return android::base::StringPrintf("cros_update_size_%" PRIuS "_hash_%s",
1010 payload_size,
1011 encoded_hash.c_str());
David Zeuthen8f191b22013-08-06 12:27:50 -07001012}
1013
Kelvin Zhangd7191032020-08-11 10:48:16 -04001014bool ConvertToOmahaInstallDate(Time time, int* out_num_days) {
David Zeuthen639aa362014-02-03 16:23:44 -08001015 time_t unix_time = time.ToTimeT();
1016 // Output of: date +"%s" --date="Jan 1, 2007 0:00 PST".
1017 const time_t kOmahaEpoch = 1167638400;
Amin Hassanib2689592019-01-13 17:04:28 -08001018 const int64_t kNumSecondsPerWeek = 7 * 24 * 3600;
David Zeuthen639aa362014-02-03 16:23:44 -08001019 const int64_t kNumDaysPerWeek = 7;
1020
1021 time_t omaha_time = unix_time - kOmahaEpoch;
1022
1023 if (omaha_time < 0)
1024 return false;
1025
1026 // Note, as per the comment in utils.h we are deliberately not
1027 // handling DST correctly.
1028
1029 int64_t num_weeks_since_omaha_epoch = omaha_time / kNumSecondsPerWeek;
1030 *out_num_days = num_weeks_since_omaha_epoch * kNumDaysPerWeek;
1031
1032 return true;
1033}
1034
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001035bool GetMinorVersion(const brillo::KeyValueStore& store,
Alex Deymob42b98d2015-07-06 17:42:38 -07001036 uint32_t* minor_version) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001037 string result;
Alex Deymob42b98d2015-07-06 17:42:38 -07001038 if (store.GetString("PAYLOAD_MINOR_VERSION", &result)) {
Allie Wood425aa972015-02-17 14:47:17 -08001039 if (!base::StringToUint(result, minor_version)) {
1040 LOG(ERROR) << "StringToUint failed when parsing delta minor version.";
1041 return false;
1042 }
Allie Wood78750a42015-02-11 15:42:11 -08001043 return true;
1044 }
1045 return false;
1046}
1047
Kelvin Zhang02fe6622021-11-01 16:37:58 -07001048bool ReadExtents(const std::string& path,
1049 const google::protobuf::RepeatedPtrField<Extent>& extents,
1050 brillo::Blob* out_data,
1051 size_t block_size) {
1052 return ReadExtents(path,
1053 {extents.begin(), extents.end()},
1054 out_data,
1055 utils::BlocksInExtents(extents) * block_size,
1056 block_size);
1057}
1058
1059bool WriteExtents(const std::string& path,
1060 const google::protobuf::RepeatedPtrField<Extent>& extents,
1061 const brillo::Blob& data,
1062 size_t block_size) {
1063 EintrSafeFileDescriptor fd;
1064 TEST_AND_RETURN_FALSE(fd.Open(path.c_str(), O_RDWR));
1065 size_t bytes_written = 0;
1066 for (const auto& ext : extents) {
1067 TEST_AND_RETURN_FALSE_ERRNO(
1068 fd.Seek(ext.start_block() * block_size, SEEK_SET));
1069 TEST_AND_RETURN_FALSE_ERRNO(
1070 fd.Write(data.data() + bytes_written, ext.num_blocks() * block_size));
1071 bytes_written += ext.num_blocks() * block_size;
1072 }
1073 return true;
1074}
Kelvin Zhang4eae81e2021-12-09 17:07:17 -08001075bool ReadExtents(const std::string& path,
1076 const vector<Extent>& extents,
1077 brillo::Blob* out_data,
1078 ssize_t out_data_size,
1079 size_t block_size) {
1080 FileDescriptorPtr fd = std::make_shared<EintrSafeFileDescriptor>();
1081 fd->Open(path.c_str(), O_RDONLY);
1082 return ReadExtents(fd, extents, out_data, out_data_size, block_size);
1083}
Kelvin Zhang02fe6622021-11-01 16:37:58 -07001084
Kelvin Zhang4eae81e2021-12-09 17:07:17 -08001085bool ReadExtents(FileDescriptorPtr fd,
1086 const google::protobuf::RepeatedPtrField<Extent>& extents,
1087 brillo::Blob* out_data,
1088 size_t block_size) {
1089 return ReadExtents(fd,
1090 {extents.begin(), extents.end()},
1091 out_data,
1092 utils::BlocksInExtents(extents) * block_size,
1093 block_size);
1094}
1095
1096bool ReadExtents(FileDescriptorPtr fd,
Amin Hassanib2689592019-01-13 17:04:28 -08001097 const vector<Extent>& extents,
1098 brillo::Blob* out_data,
1099 ssize_t out_data_size,
Allie Wood56873452015-03-27 17:48:40 -07001100 size_t block_size) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -07001101 brillo::Blob data(out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001102 ssize_t bytes_read = 0;
Allie Wood56873452015-03-27 17:48:40 -07001103
Gilad Arnold41e34742015-05-11 11:31:50 -07001104 for (const Extent& extent : extents) {
Allie Wood56873452015-03-27 17:48:40 -07001105 ssize_t bytes_read_this_iteration = 0;
1106 ssize_t bytes = extent.num_blocks() * block_size;
Kelvin Zhang02fe6622021-11-01 16:37:58 -07001107 TEST_LE(bytes_read + bytes, out_data_size);
Allie Wood56873452015-03-27 17:48:40 -07001108 TEST_AND_RETURN_FALSE(utils::PReadAll(fd,
1109 &data[bytes_read],
1110 bytes,
1111 extent.start_block() * block_size,
1112 &bytes_read_this_iteration));
1113 TEST_AND_RETURN_FALSE(bytes_read_this_iteration == bytes);
1114 bytes_read += bytes_read_this_iteration;
1115 }
1116 TEST_AND_RETURN_FALSE(out_data_size == bytes_read);
1117 *out_data = data;
1118 return true;
1119}
1120
Matt Ziegelbaum91ba9be2020-06-10 16:56:40 -04001121bool GetVpdValue(string key, string* result) {
1122 int exit_code = 0;
1123 string value, error;
1124 vector<string> cmd = {"vpd_get_value", key};
1125 if (!chromeos_update_engine::Subprocess::SynchronousExec(
1126 cmd, &exit_code, &value, &error) ||
1127 exit_code) {
1128 LOG(ERROR) << "Failed to get vpd key for " << value
1129 << " with exit code: " << exit_code << " and error: " << error;
1130 return false;
1131 } else if (!error.empty()) {
1132 LOG(INFO) << "vpd_get_value succeeded but with following errors: " << error;
1133 }
1134
1135 base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
1136 *result = value;
1137 return true;
1138}
1139
Alex Deymodd132f32015-09-14 19:12:07 -07001140bool GetBootId(string* boot_id) {
1141 TEST_AND_RETURN_FALSE(
1142 base::ReadFileToString(base::FilePath(kBootIdPath), boot_id));
1143 base::TrimWhitespaceASCII(*boot_id, base::TRIM_TRAILING, boot_id);
1144 return true;
1145}
1146
Marton Hunyadya0302682018-05-16 18:52:13 +02001147int VersionPrefix(const std::string& version) {
1148 if (version.empty()) {
1149 return 0;
1150 }
1151 vector<string> tokens = base::SplitString(
1152 version, ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
Daniel Zheng3e881aa2022-09-07 22:10:29 +00001153 int value{};
Marton Hunyadya0302682018-05-16 18:52:13 +02001154 if (tokens.empty() || !base::StringToInt(tokens[0], &value))
1155 return -1; // Target version is invalid.
1156 return value;
1157}
1158
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001159void ParseRollbackKeyVersion(const string& raw_version,
1160 uint16_t* high_version,
1161 uint16_t* low_version) {
1162 DCHECK(high_version);
1163 DCHECK(low_version);
1164 *high_version = numeric_limits<uint16_t>::max();
1165 *low_version = numeric_limits<uint16_t>::max();
1166
1167 vector<string> parts = base::SplitString(
1168 raw_version, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
1169 if (parts.size() != 2) {
1170 // The version string must have exactly one period.
1171 return;
1172 }
1173
Daniel Zheng3e881aa2022-09-07 22:10:29 +00001174 int high{};
1175 int low{};
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001176 if (!(base::StringToInt(parts[0], &high) &&
1177 base::StringToInt(parts[1], &low))) {
1178 // Both parts of the version could not be parsed correctly.
1179 return;
1180 }
1181
1182 if (high >= 0 && high < numeric_limits<uint16_t>::max() && low >= 0 &&
1183 low < numeric_limits<uint16_t>::max()) {
1184 *high_version = static_cast<uint16_t>(high);
1185 *low_version = static_cast<uint16_t>(low);
1186 }
1187}
1188
Kyeongkab.Nam500ca132019-06-26 13:48:07 +09001189string GetFilePath(int fd) {
1190 base::FilePath proc("/proc/self/fd/" + std::to_string(fd));
1191 base::FilePath file_name;
1192
1193 if (!base::ReadSymbolicLink(proc, &file_name)) {
1194 return "not found";
1195 }
1196 return file_name.value();
1197}
1198
Yifan Hongc80de2d2020-02-25 17:13:53 -08001199string GetTimeAsString(time_t utime) {
Kelvin Zhang0c184242024-10-25 11:19:27 -07001200 struct tm tm {};
Yifan Hongc80de2d2020-02-25 17:13:53 -08001201 CHECK_EQ(localtime_r(&utime, &tm), &tm);
1202 char str[16];
1203 CHECK_EQ(strftime(str, sizeof(str), "%Y%m%d-%H%M%S", &tm), 15u);
1204 return str;
1205}
1206
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001207string GetExclusionName(const string& str_to_convert) {
Kokoa Matsuda1f46f5b2024-10-18 16:00:05 +09001208 return std::format("{}", base::StringPieceHash()(str_to_convert));
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001209}
1210
Kelvin Zhang636ba2f2022-02-09 14:40:22 -08001211static bool ParseTimestamp(std::string_view str, int64_t* out) {
1212 if (!base::StringToInt64(base::StringPiece(str.data(), str.size()), out)) {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001213 LOG(WARNING) << "Invalid timestamp: " << str;
1214 return false;
1215 }
1216 return true;
1217}
1218
Kelvin Zhang636ba2f2022-02-09 14:40:22 -08001219ErrorCode IsTimestampNewer(const std::string_view old_version,
1220 const std::string_view new_version) {
Kelvin Zhangd7191032020-08-11 10:48:16 -04001221 if (old_version.empty() || new_version.empty()) {
1222 LOG(WARNING)
1223 << "One of old/new timestamp is empty, permit update anyway. Old: "
1224 << old_version << " New: " << new_version;
Yifan Hong87029332020-09-01 17:20:08 -07001225 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001226 }
1227 int64_t old_ver = 0;
Yifan Hong87029332020-09-01 17:20:08 -07001228 if (!ParseTimestamp(old_version, &old_ver)) {
1229 return ErrorCode::kError;
1230 }
Kelvin Zhangd7191032020-08-11 10:48:16 -04001231 int64_t new_ver = 0;
Yifan Hong87029332020-09-01 17:20:08 -07001232 if (!ParseTimestamp(new_version, &new_ver)) {
1233 return ErrorCode::kDownloadManifestParseError;
1234 }
1235 if (old_ver > new_ver) {
1236 return ErrorCode::kPayloadTimestampError;
1237 }
1238 return ErrorCode::kSuccess;
Kelvin Zhangd7191032020-08-11 10:48:16 -04001239}
1240
Kelvin Zhang4bb49202021-07-08 21:39:05 -04001241std::unique_ptr<android::base::MappedFile> GetReadonlyZeroBlock(size_t size) {
1242 android::base::unique_fd fd{HANDLE_EINTR(open("/dev/zero", O_RDONLY))};
1243 return android::base::MappedFile::FromFd(fd, 0, size, PROT_READ);
1244}
1245
Kelvin Zhang3fe49642021-10-04 15:35:02 -07001246std::string_view GetReadonlyZeroString(size_t size) {
1247 // Reserve 512MB of Virtual Address Space. No actual memory will be used.
1248 static auto zero_block = GetReadonlyZeroBlock(1024 * 1024 * 512);
1249 if (size > zero_block->size()) {
1250 auto larger_block = GetReadonlyZeroBlock(size);
1251 zero_block = std::move(larger_block);
1252 }
1253 return {zero_block->data(), size};
1254}
1255
adlr@google.com3defe6a2009-12-04 20:57:17 +00001256} // namespace utils
1257
Kelvin Zhang20982a52021-08-13 12:31:16 -07001258std::string HexEncode(const brillo::Blob& blob) noexcept {
1259 return base::HexEncode(blob.data(), blob.size());
1260}
1261
Kelvin Zhang3fe49642021-10-04 15:35:02 -07001262std::string HexEncode(const std::string_view blob) noexcept {
1263 return base::HexEncode(blob.data(), blob.size());
1264}
1265
Kelvin Zhang760c3342022-02-08 13:41:49 -08001266[[nodiscard]] std::string_view ToStringView(
1267 const std::vector<unsigned char>& blob) noexcept {
1268 return std::string_view{reinterpret_cast<const char*>(blob.data()),
1269 blob.size()};
1270}
1271
1272[[nodiscard]] std::string_view ToStringView(const void* data,
1273 size_t size) noexcept {
1274 return std::string_view(reinterpret_cast<const char*>(data), size);
1275}
1276
adlr@google.com3defe6a2009-12-04 20:57:17 +00001277} // namespace chromeos_update_engine