xref: /aosp_15_r20/system/update_engine/common/utils.h (revision 5a9231315b4521097b8dc3750bc806fcafe0c72f)
1*5a923131SAndroid Build Coastguard Worker //
2*5a923131SAndroid Build Coastguard Worker // Copyright (C) 2012 The Android Open Source Project
3*5a923131SAndroid Build Coastguard Worker //
4*5a923131SAndroid Build Coastguard Worker // Licensed under the Apache License, Version 2.0 (the "License");
5*5a923131SAndroid Build Coastguard Worker // you may not use this file except in compliance with the License.
6*5a923131SAndroid Build Coastguard Worker // You may obtain a copy of the License at
7*5a923131SAndroid Build Coastguard Worker //
8*5a923131SAndroid Build Coastguard Worker //      http://www.apache.org/licenses/LICENSE-2.0
9*5a923131SAndroid Build Coastguard Worker //
10*5a923131SAndroid Build Coastguard Worker // Unless required by applicable law or agreed to in writing, software
11*5a923131SAndroid Build Coastguard Worker // distributed under the License is distributed on an "AS IS" BASIS,
12*5a923131SAndroid Build Coastguard Worker // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*5a923131SAndroid Build Coastguard Worker // See the License for the specific language governing permissions and
14*5a923131SAndroid Build Coastguard Worker // limitations under the License.
15*5a923131SAndroid Build Coastguard Worker //
16*5a923131SAndroid Build Coastguard Worker 
17*5a923131SAndroid Build Coastguard Worker #ifndef UPDATE_ENGINE_COMMON_UTILS_H_
18*5a923131SAndroid Build Coastguard Worker #define UPDATE_ENGINE_COMMON_UTILS_H_
19*5a923131SAndroid Build Coastguard Worker 
20*5a923131SAndroid Build Coastguard Worker #include <errno.h>
21*5a923131SAndroid Build Coastguard Worker #include <sys/types.h>
22*5a923131SAndroid Build Coastguard Worker #include <time.h>
23*5a923131SAndroid Build Coastguard Worker #include <unistd.h>
24*5a923131SAndroid Build Coastguard Worker 
25*5a923131SAndroid Build Coastguard Worker #include <algorithm>
26*5a923131SAndroid Build Coastguard Worker #include <limits>
27*5a923131SAndroid Build Coastguard Worker #include <map>
28*5a923131SAndroid Build Coastguard Worker #include <memory>
29*5a923131SAndroid Build Coastguard Worker #include <set>
30*5a923131SAndroid Build Coastguard Worker #include <string>
31*5a923131SAndroid Build Coastguard Worker #include <vector>
32*5a923131SAndroid Build Coastguard Worker 
33*5a923131SAndroid Build Coastguard Worker #include <android-base/strings.h>
34*5a923131SAndroid Build Coastguard Worker #include <android-base/mapped_file.h>
35*5a923131SAndroid Build Coastguard Worker #include <android-base/scopeguard.h>
36*5a923131SAndroid Build Coastguard Worker #include <base/files/file_path.h>
37*5a923131SAndroid Build Coastguard Worker #include <base/posix/eintr_wrapper.h>
38*5a923131SAndroid Build Coastguard Worker #include <base/strings/string_number_conversions.h>
39*5a923131SAndroid Build Coastguard Worker #include <base/time/time.h>
40*5a923131SAndroid Build Coastguard Worker #include <brillo/key_value_store.h>
41*5a923131SAndroid Build Coastguard Worker #include <brillo/secure_blob.h>
42*5a923131SAndroid Build Coastguard Worker 
43*5a923131SAndroid Build Coastguard Worker #include "update_engine/common/action.h"
44*5a923131SAndroid Build Coastguard Worker #include "update_engine/common/action_processor.h"
45*5a923131SAndroid Build Coastguard Worker #include "update_engine/common/constants.h"
46*5a923131SAndroid Build Coastguard Worker #include "update_engine/payload_consumer/file_descriptor.h"
47*5a923131SAndroid Build Coastguard Worker #include "update_engine/update_metadata.pb.h"
48*5a923131SAndroid Build Coastguard Worker 
49*5a923131SAndroid Build Coastguard Worker namespace chromeos_update_engine {
50*5a923131SAndroid Build Coastguard Worker 
51*5a923131SAndroid Build Coastguard Worker namespace utils {
52*5a923131SAndroid Build Coastguard Worker 
53*5a923131SAndroid Build Coastguard Worker // Formats |vec_str| as a string of the form ["<elem1>", "<elem2>"].
54*5a923131SAndroid Build Coastguard Worker // Does no escaping, only use this for presentation in error messages.
55*5a923131SAndroid Build Coastguard Worker std::string StringVectorToString(const std::vector<std::string>& vec_str);
56*5a923131SAndroid Build Coastguard Worker 
57*5a923131SAndroid Build Coastguard Worker // Calculates the p2p file id from payload hash and size
58*5a923131SAndroid Build Coastguard Worker std::string CalculateP2PFileId(const brillo::Blob& payload_hash,
59*5a923131SAndroid Build Coastguard Worker                                size_t payload_size);
60*5a923131SAndroid Build Coastguard Worker 
61*5a923131SAndroid Build Coastguard Worker // Writes the data passed to path. The file at path will be overwritten if it
62*5a923131SAndroid Build Coastguard Worker // exists. Returns true on success, false otherwise.
63*5a923131SAndroid Build Coastguard Worker bool WriteFile(const char* path, const void* data, size_t data_len);
64*5a923131SAndroid Build Coastguard Worker 
65*5a923131SAndroid Build Coastguard Worker // Calls write() or pwrite() repeatedly until all count bytes at buf are
66*5a923131SAndroid Build Coastguard Worker // written to fd or an error occurs. Returns true on success.
67*5a923131SAndroid Build Coastguard Worker bool WriteAll(int fd, const void* buf, size_t count);
68*5a923131SAndroid Build Coastguard Worker bool PWriteAll(int fd, const void* buf, size_t count, off_t offset);
69*5a923131SAndroid Build Coastguard Worker 
70*5a923131SAndroid Build Coastguard Worker bool WriteAll(FileDescriptor* fd, const void* buf, size_t count);
71*5a923131SAndroid Build Coastguard Worker 
WriteAll(const FileDescriptorPtr & fd,const void * buf,size_t count)72*5a923131SAndroid Build Coastguard Worker constexpr bool WriteAll(const FileDescriptorPtr& fd,
73*5a923131SAndroid Build Coastguard Worker                         const void* buf,
74*5a923131SAndroid Build Coastguard Worker                         size_t count) {
75*5a923131SAndroid Build Coastguard Worker   return WriteAll(fd.get(), buf, count);
76*5a923131SAndroid Build Coastguard Worker }
77*5a923131SAndroid Build Coastguard Worker // WriteAll writes data at specified offset, but it modifies file position.
78*5a923131SAndroid Build Coastguard Worker bool WriteAll(FileDescriptorPtr* fd, const void* buf, size_t count, off_t off);
79*5a923131SAndroid Build Coastguard Worker 
80*5a923131SAndroid Build Coastguard Worker // https://man7.org/linux/man-pages/man2/pread.2.html
81*5a923131SAndroid Build Coastguard Worker // PWriteAll writes data at specified offset, but it DOES NOT modify file
82*5a923131SAndroid Build Coastguard Worker // position. Behaves similar to linux' pwrite syscall.
83*5a923131SAndroid Build Coastguard Worker bool PWriteAll(const FileDescriptorPtr& fd,
84*5a923131SAndroid Build Coastguard Worker                const void* buf,
85*5a923131SAndroid Build Coastguard Worker                size_t count,
86*5a923131SAndroid Build Coastguard Worker                off_t offset);
87*5a923131SAndroid Build Coastguard Worker 
88*5a923131SAndroid Build Coastguard Worker // Calls read() repeatedly until |count| bytes are read or EOF or EWOULDBLOCK
89*5a923131SAndroid Build Coastguard Worker // is reached. Returns whether all read() calls succeeded (including EWOULDBLOCK
90*5a923131SAndroid Build Coastguard Worker // as a success case), sets |eof| to whether the eof was reached and sets
91*5a923131SAndroid Build Coastguard Worker // |out_bytes_read| to the actual number of bytes read regardless of the return
92*5a923131SAndroid Build Coastguard Worker // value.
93*5a923131SAndroid Build Coastguard Worker bool ReadAll(
94*5a923131SAndroid Build Coastguard Worker     int fd, void* buf, size_t count, size_t* out_bytes_read, bool* eof);
95*5a923131SAndroid Build Coastguard Worker 
96*5a923131SAndroid Build Coastguard Worker // Calls pread() repeatedly until count bytes are read, or EOF is reached.
97*5a923131SAndroid Build Coastguard Worker // Returns number of bytes read in *bytes_read. Returns true on success.
98*5a923131SAndroid Build Coastguard Worker bool PReadAll(
99*5a923131SAndroid Build Coastguard Worker     int fd, void* buf, size_t count, off_t offset, ssize_t* out_bytes_read);
100*5a923131SAndroid Build Coastguard Worker 
101*5a923131SAndroid Build Coastguard Worker // Reads data at specified offset, this function does change file position.
102*5a923131SAndroid Build Coastguard Worker 
103*5a923131SAndroid Build Coastguard Worker bool ReadAll(FileDescriptor* fd,
104*5a923131SAndroid Build Coastguard Worker              void* buf,
105*5a923131SAndroid Build Coastguard Worker              size_t count,
106*5a923131SAndroid Build Coastguard Worker              off_t offset,
107*5a923131SAndroid Build Coastguard Worker              ssize_t* out_bytes_read);
108*5a923131SAndroid Build Coastguard Worker 
ReadAll(const FileDescriptorPtr & fd,void * buf,size_t count,off_t offset,ssize_t * out_bytes_read)109*5a923131SAndroid Build Coastguard Worker constexpr bool ReadAll(const FileDescriptorPtr& fd,
110*5a923131SAndroid Build Coastguard Worker                        void* buf,
111*5a923131SAndroid Build Coastguard Worker                        size_t count,
112*5a923131SAndroid Build Coastguard Worker                        off_t offset,
113*5a923131SAndroid Build Coastguard Worker                        ssize_t* out_bytes_read) {
114*5a923131SAndroid Build Coastguard Worker   return ReadAll(fd.get(), buf, count, offset, out_bytes_read);
115*5a923131SAndroid Build Coastguard Worker }
116*5a923131SAndroid Build Coastguard Worker 
117*5a923131SAndroid Build Coastguard Worker // https://man7.org/linux/man-pages/man2/pread.2.html
118*5a923131SAndroid Build Coastguard Worker // Reads data at specified offset, this function DOES NOT change file position.
119*5a923131SAndroid Build Coastguard Worker // Behavior is similar to linux's pread syscall.
120*5a923131SAndroid Build Coastguard Worker bool PReadAll(FileDescriptor* fd,
121*5a923131SAndroid Build Coastguard Worker               void* buf,
122*5a923131SAndroid Build Coastguard Worker               size_t count,
123*5a923131SAndroid Build Coastguard Worker               off_t offset,
124*5a923131SAndroid Build Coastguard Worker               ssize_t* out_bytes_read);
125*5a923131SAndroid Build Coastguard Worker 
PReadAll(const FileDescriptorPtr & fd,void * buf,size_t count,off_t offset,ssize_t * out_bytes_read)126*5a923131SAndroid Build Coastguard Worker constexpr bool PReadAll(const FileDescriptorPtr& fd,
127*5a923131SAndroid Build Coastguard Worker                         void* buf,
128*5a923131SAndroid Build Coastguard Worker                         size_t count,
129*5a923131SAndroid Build Coastguard Worker                         off_t offset,
130*5a923131SAndroid Build Coastguard Worker                         ssize_t* out_bytes_read) {
131*5a923131SAndroid Build Coastguard Worker   return PReadAll(fd.get(), buf, count, offset, out_bytes_read);
132*5a923131SAndroid Build Coastguard Worker }
133*5a923131SAndroid Build Coastguard Worker 
134*5a923131SAndroid Build Coastguard Worker // Opens |path| for reading and appends its entire content to the container
135*5a923131SAndroid Build Coastguard Worker // pointed to by |out_p|. Returns true upon successfully reading all of the
136*5a923131SAndroid Build Coastguard Worker // file's content, false otherwise, in which case the state of the output
137*5a923131SAndroid Build Coastguard Worker // container is unknown. ReadFileChunk starts reading the file from |offset|; if
138*5a923131SAndroid Build Coastguard Worker // |size| is not -1, only up to |size| bytes are read in.
139*5a923131SAndroid Build Coastguard Worker bool ReadFile(const std::string& path, brillo::Blob* out_p);
140*5a923131SAndroid Build Coastguard Worker bool ReadFile(const std::string& path, std::string* out_p);
141*5a923131SAndroid Build Coastguard Worker bool ReadFileChunk(const std::string& path,
142*5a923131SAndroid Build Coastguard Worker                    off_t offset,
143*5a923131SAndroid Build Coastguard Worker                    off_t size,
144*5a923131SAndroid Build Coastguard Worker                    brillo::Blob* out_p);
145*5a923131SAndroid Build Coastguard Worker 
146*5a923131SAndroid Build Coastguard Worker // Invokes |cmd| in a pipe and appends its stdout to the container pointed to by
147*5a923131SAndroid Build Coastguard Worker // |out_p|. Returns true upon successfully reading all of the output, false
148*5a923131SAndroid Build Coastguard Worker // otherwise, in which case the state of the output container is unknown.
149*5a923131SAndroid Build Coastguard Worker bool ReadPipe(const std::string& cmd, std::string* out_p);
150*5a923131SAndroid Build Coastguard Worker 
151*5a923131SAndroid Build Coastguard Worker // Returns the size of the block device at the file descriptor fd. If an error
152*5a923131SAndroid Build Coastguard Worker // occurs, -1 is returned.
153*5a923131SAndroid Build Coastguard Worker off_t BlockDevSize(int fd);
154*5a923131SAndroid Build Coastguard Worker 
155*5a923131SAndroid Build Coastguard Worker // Returns the size of the file at path, or the file descriptor fd. If the file
156*5a923131SAndroid Build Coastguard Worker // is actually a block device, this function will automatically call
157*5a923131SAndroid Build Coastguard Worker // BlockDevSize. If the file doesn't exist or some error occurrs, -1 is
158*5a923131SAndroid Build Coastguard Worker // returned.
159*5a923131SAndroid Build Coastguard Worker off_t FileSize(const std::string& path);
160*5a923131SAndroid Build Coastguard Worker off_t FileSize(int fd);
161*5a923131SAndroid Build Coastguard Worker 
162*5a923131SAndroid Build Coastguard Worker bool SendFile(int out_fd, int in_fd, size_t count);
163*5a923131SAndroid Build Coastguard Worker 
164*5a923131SAndroid Build Coastguard Worker bool FsyncDirectoryContents(const char* dirname);
165*5a923131SAndroid Build Coastguard Worker bool FsyncDirectory(const char* dirname);
166*5a923131SAndroid Build Coastguard Worker bool DeleteDirectory(const char* dirname);
167*5a923131SAndroid Build Coastguard Worker bool WriteStringToFileAtomic(const std::string& path, std::string_view content);
168*5a923131SAndroid Build Coastguard Worker 
169*5a923131SAndroid Build Coastguard Worker // Returns true if the file exists for sure. Returns false if it doesn't exist,
170*5a923131SAndroid Build Coastguard Worker // or an error occurs.
171*5a923131SAndroid Build Coastguard Worker bool FileExists(const char* path);
172*5a923131SAndroid Build Coastguard Worker 
173*5a923131SAndroid Build Coastguard Worker // Returns true if |path| exists and is a symbolic link.
174*5a923131SAndroid Build Coastguard Worker bool IsSymlink(const char* path);
175*5a923131SAndroid Build Coastguard Worker 
176*5a923131SAndroid Build Coastguard Worker // Return true iff |path| exists and is a regular file
177*5a923131SAndroid Build Coastguard Worker bool IsRegFile(const char* path);
178*5a923131SAndroid Build Coastguard Worker 
179*5a923131SAndroid Build Coastguard Worker // If |base_filename_template| is neither absolute (starts with "/") nor
180*5a923131SAndroid Build Coastguard Worker // explicitly relative to the current working directory (starts with "./" or
181*5a923131SAndroid Build Coastguard Worker // "../"), then it is prepended the system's temporary directory. On success,
182*5a923131SAndroid Build Coastguard Worker // stores the name of the new temporary file in |filename|. If |fd| is
183*5a923131SAndroid Build Coastguard Worker // non-null, the file descriptor returned by mkstemp is written to it and
184*5a923131SAndroid Build Coastguard Worker // kept open; otherwise, it is closed. The template must end with "XXXXXX".
185*5a923131SAndroid Build Coastguard Worker // Returns true on success.
186*5a923131SAndroid Build Coastguard Worker bool MakeTempFile(const std::string& base_filename_template,
187*5a923131SAndroid Build Coastguard Worker                   std::string* filename,
188*5a923131SAndroid Build Coastguard Worker                   int* fd);
189*5a923131SAndroid Build Coastguard Worker 
190*5a923131SAndroid Build Coastguard Worker // Splits the partition device name into the block device name and partition
191*5a923131SAndroid Build Coastguard Worker // number. For example, "/dev/sda3" will be split into {"/dev/sda", 3} and
192*5a923131SAndroid Build Coastguard Worker // "/dev/mmcblk0p2" into {"/dev/mmcblk0", 2}
193*5a923131SAndroid Build Coastguard Worker // Returns false when malformed device name is passed in.
194*5a923131SAndroid Build Coastguard Worker // If both output parameters are omitted (null), can be used
195*5a923131SAndroid Build Coastguard Worker // just to test the validity of the device name. Note that the function
196*5a923131SAndroid Build Coastguard Worker // simply checks if the device name looks like a valid device, no other
197*5a923131SAndroid Build Coastguard Worker // checks are performed (i.e. it doesn't check if the device actually exists).
198*5a923131SAndroid Build Coastguard Worker bool SplitPartitionName(const std::string& partition_name,
199*5a923131SAndroid Build Coastguard Worker                         std::string* out_disk_name,
200*5a923131SAndroid Build Coastguard Worker                         int* out_partition_num);
201*5a923131SAndroid Build Coastguard Worker 
202*5a923131SAndroid Build Coastguard Worker // Builds a partition device name from the block device name and partition
203*5a923131SAndroid Build Coastguard Worker // number. For example:
204*5a923131SAndroid Build Coastguard Worker // {"/dev/sda", 1} => "/dev/sda1"
205*5a923131SAndroid Build Coastguard Worker // {"/dev/mmcblk2", 12} => "/dev/mmcblk2p12"
206*5a923131SAndroid Build Coastguard Worker // Returns empty string when invalid parameters are passed in
207*5a923131SAndroid Build Coastguard Worker std::string MakePartitionName(const std::string& disk_name, int partition_num);
208*5a923131SAndroid Build Coastguard Worker 
209*5a923131SAndroid Build Coastguard Worker // Set the read-only attribute on the block device |device| to the value passed
210*5a923131SAndroid Build Coastguard Worker // in |read_only|. Return whether the operation succeeded.
211*5a923131SAndroid Build Coastguard Worker bool SetBlockDeviceReadOnly(const std::string& device, bool read_only);
212*5a923131SAndroid Build Coastguard Worker 
213*5a923131SAndroid Build Coastguard Worker // Synchronously mount or unmount a filesystem. Return true on success.
214*5a923131SAndroid Build Coastguard Worker // When mounting, it will attempt to mount the device as the passed filesystem
215*5a923131SAndroid Build Coastguard Worker // type |type|, with the passed |flags| options. If |type| is empty, "ext2",
216*5a923131SAndroid Build Coastguard Worker // "ext3", "ext4" and "squashfs" will be tried.
217*5a923131SAndroid Build Coastguard Worker bool MountFilesystem(const std::string& device,
218*5a923131SAndroid Build Coastguard Worker                      const std::string& mountpoint,
219*5a923131SAndroid Build Coastguard Worker                      unsigned long flags,  // NOLINT(runtime/int)
220*5a923131SAndroid Build Coastguard Worker                      const std::string& type,
221*5a923131SAndroid Build Coastguard Worker                      const std::string& fs_mount_options);
222*5a923131SAndroid Build Coastguard Worker bool UnmountFilesystem(const std::string& mountpoint);
223*5a923131SAndroid Build Coastguard Worker 
224*5a923131SAndroid Build Coastguard Worker // Return whether the passed |mountpoint| path is a directory where a filesystem
225*5a923131SAndroid Build Coastguard Worker // is mounted. Due to detection mechanism limitations, when used on directories
226*5a923131SAndroid Build Coastguard Worker // where another part of the tree was bind mounted returns true only if bind
227*5a923131SAndroid Build Coastguard Worker // mounted on top of a different filesystem (not inside the same filesystem).
228*5a923131SAndroid Build Coastguard Worker bool IsMountpoint(const std::string& mountpoint);
229*5a923131SAndroid Build Coastguard Worker 
230*5a923131SAndroid Build Coastguard Worker // Returns a human-readable string with the file format based on magic constants
231*5a923131SAndroid Build Coastguard Worker // on the header of the file.
232*5a923131SAndroid Build Coastguard Worker std::string GetFileFormat(const std::string& path);
233*5a923131SAndroid Build Coastguard Worker 
234*5a923131SAndroid Build Coastguard Worker // Returns the string representation of the given UTC time.
235*5a923131SAndroid Build Coastguard Worker // such as "11/14/2011 14:05:30 GMT".
236*5a923131SAndroid Build Coastguard Worker std::string ToString(const base::Time utc_time);
237*5a923131SAndroid Build Coastguard Worker 
238*5a923131SAndroid Build Coastguard Worker // Returns true or false depending on the value of b.
239*5a923131SAndroid Build Coastguard Worker std::string ToString(bool b);
240*5a923131SAndroid Build Coastguard Worker 
241*5a923131SAndroid Build Coastguard Worker // Returns a string representation of the given enum.
242*5a923131SAndroid Build Coastguard Worker std::string ToString(DownloadSource source);
243*5a923131SAndroid Build Coastguard Worker 
244*5a923131SAndroid Build Coastguard Worker // Returns a string representation of the given enum.
245*5a923131SAndroid Build Coastguard Worker std::string ToString(PayloadType payload_type);
246*5a923131SAndroid Build Coastguard Worker 
247*5a923131SAndroid Build Coastguard Worker // Fuzzes an integer |value| randomly in the range:
248*5a923131SAndroid Build Coastguard Worker // [value - range / 2, value + range - range / 2]
249*5a923131SAndroid Build Coastguard Worker int FuzzInt(int value, unsigned int range);
250*5a923131SAndroid Build Coastguard Worker 
251*5a923131SAndroid Build Coastguard Worker // Log a string in hex to LOG(INFO). Useful for debugging.
252*5a923131SAndroid Build Coastguard Worker void HexDumpArray(const uint8_t* const arr, const size_t length);
HexDumpString(const std::string & str)253*5a923131SAndroid Build Coastguard Worker inline void HexDumpString(const std::string& str) {
254*5a923131SAndroid Build Coastguard Worker   HexDumpArray(reinterpret_cast<const uint8_t*>(str.data()), str.size());
255*5a923131SAndroid Build Coastguard Worker }
HexDumpVector(const brillo::Blob & vect)256*5a923131SAndroid Build Coastguard Worker inline void HexDumpVector(const brillo::Blob& vect) {
257*5a923131SAndroid Build Coastguard Worker   HexDumpArray(vect.data(), vect.size());
258*5a923131SAndroid Build Coastguard Worker }
259*5a923131SAndroid Build Coastguard Worker 
260*5a923131SAndroid Build Coastguard Worker template <typename T>
VectorIndexOf(const std::vector<T> & vect,const T & value,typename std::vector<T>::size_type * out_index)261*5a923131SAndroid Build Coastguard Worker bool VectorIndexOf(const std::vector<T>& vect,
262*5a923131SAndroid Build Coastguard Worker                    const T& value,
263*5a923131SAndroid Build Coastguard Worker                    typename std::vector<T>::size_type* out_index) {
264*5a923131SAndroid Build Coastguard Worker   typename std::vector<T>::const_iterator it =
265*5a923131SAndroid Build Coastguard Worker       std::find(vect.begin(), vect.end(), value);
266*5a923131SAndroid Build Coastguard Worker   if (it == vect.end()) {
267*5a923131SAndroid Build Coastguard Worker     return false;
268*5a923131SAndroid Build Coastguard Worker   } else {
269*5a923131SAndroid Build Coastguard Worker     *out_index = it - vect.begin();
270*5a923131SAndroid Build Coastguard Worker     return true;
271*5a923131SAndroid Build Coastguard Worker   }
272*5a923131SAndroid Build Coastguard Worker }
273*5a923131SAndroid Build Coastguard Worker 
274*5a923131SAndroid Build Coastguard Worker // Return the total number of blocks in the passed |extents| collection.
275*5a923131SAndroid Build Coastguard Worker template <class T>
BlocksInExtents(const T & extents)276*5a923131SAndroid Build Coastguard Worker uint64_t BlocksInExtents(const T& extents) {
277*5a923131SAndroid Build Coastguard Worker   uint64_t sum = 0;
278*5a923131SAndroid Build Coastguard Worker   for (const auto& ext : extents) {
279*5a923131SAndroid Build Coastguard Worker     sum += ext.num_blocks();
280*5a923131SAndroid Build Coastguard Worker   }
281*5a923131SAndroid Build Coastguard Worker   return sum;
282*5a923131SAndroid Build Coastguard Worker }
283*5a923131SAndroid Build Coastguard Worker 
284*5a923131SAndroid Build Coastguard Worker // Converts seconds into human readable notation including days, hours, minutes
285*5a923131SAndroid Build Coastguard Worker // and seconds. For example, 185 will yield 3m5s, 4300 will yield 1h11m40s, and
286*5a923131SAndroid Build Coastguard Worker // 360000 will yield 4d4h0m0s.  Zero padding not applied. Seconds are always
287*5a923131SAndroid Build Coastguard Worker // shown in the result.
288*5a923131SAndroid Build Coastguard Worker std::string FormatSecs(unsigned secs);
289*5a923131SAndroid Build Coastguard Worker 
290*5a923131SAndroid Build Coastguard Worker // Converts a TimeDelta into human readable notation including days, hours,
291*5a923131SAndroid Build Coastguard Worker // minutes, seconds and fractions of a second down to microsecond granularity,
292*5a923131SAndroid Build Coastguard Worker // as necessary; for example, an output of 5d2h0m15.053s means that the input
293*5a923131SAndroid Build Coastguard Worker // time was precise to the milliseconds only. Zero padding not applied, except
294*5a923131SAndroid Build Coastguard Worker // for fractions. Seconds are always shown, but fractions thereof are only shown
295*5a923131SAndroid Build Coastguard Worker // when applicable. If |delta| is negative, the output will have a leading '-'
296*5a923131SAndroid Build Coastguard Worker // followed by the absolute duration.
297*5a923131SAndroid Build Coastguard Worker std::string FormatTimeDelta(base::TimeDelta delta);
298*5a923131SAndroid Build Coastguard Worker 
299*5a923131SAndroid Build Coastguard Worker // This method transforms the given error code to be suitable for UMA and
300*5a923131SAndroid Build Coastguard Worker // for error classification purposes by removing the higher order bits and
301*5a923131SAndroid Build Coastguard Worker // aggregating error codes beyond the enum range, etc. This method is
302*5a923131SAndroid Build Coastguard Worker // idempotent, i.e. if called with a value previously returned by this method,
303*5a923131SAndroid Build Coastguard Worker // it'll return the same value again.
304*5a923131SAndroid Build Coastguard Worker ErrorCode GetBaseErrorCode(ErrorCode code);
305*5a923131SAndroid Build Coastguard Worker 
306*5a923131SAndroid Build Coastguard Worker // Converts |time| to an Omaha InstallDate which is defined as "the
307*5a923131SAndroid Build Coastguard Worker // number of PST8PDT calendar weeks since Jan 1st 2007 0:00 PST, times
308*5a923131SAndroid Build Coastguard Worker // seven" with PST8PDT defined as "Pacific Time" (e.g. UTC-07:00 if
309*5a923131SAndroid Build Coastguard Worker // daylight savings is observed and UTC-08:00 otherwise.)
310*5a923131SAndroid Build Coastguard Worker //
311*5a923131SAndroid Build Coastguard Worker // If the passed in |time| variable is before Monday January 1st 2007
312*5a923131SAndroid Build Coastguard Worker // 0:00 PST, False is returned and the value returned in
313*5a923131SAndroid Build Coastguard Worker // |out_num_days| is undefined. Otherwise the number of PST8PDT
314*5a923131SAndroid Build Coastguard Worker // calendar weeks since that date times seven is returned in
315*5a923131SAndroid Build Coastguard Worker // |out_num_days| and the function returns True.
316*5a923131SAndroid Build Coastguard Worker //
317*5a923131SAndroid Build Coastguard Worker // (NOTE: This function does not currently take daylight savings time
318*5a923131SAndroid Build Coastguard Worker // into account so the result may up to one hour off. This is because
319*5a923131SAndroid Build Coastguard Worker // the glibc date and timezone routines depend on the TZ environment
320*5a923131SAndroid Build Coastguard Worker // variable and changing environment variables is not thread-safe.
321*5a923131SAndroid Build Coastguard Worker bool ConvertToOmahaInstallDate(base::Time time, int* out_num_days);
322*5a923131SAndroid Build Coastguard Worker 
323*5a923131SAndroid Build Coastguard Worker // Look for the minor version value in the passed |store| and set
324*5a923131SAndroid Build Coastguard Worker // |minor_version| to that value. Return whether the value was found and valid.
325*5a923131SAndroid Build Coastguard Worker bool GetMinorVersion(const brillo::KeyValueStore& store,
326*5a923131SAndroid Build Coastguard Worker                      uint32_t* minor_version);
327*5a923131SAndroid Build Coastguard Worker 
328*5a923131SAndroid Build Coastguard Worker // This function reads the specified data in |extents| into |out_data|. The
329*5a923131SAndroid Build Coastguard Worker // extents are read from the file at |path|. |out_data_size| is the size of
330*5a923131SAndroid Build Coastguard Worker // |out_data|. Returns false if the number of bytes to read given in
331*5a923131SAndroid Build Coastguard Worker // |extents| does not equal |out_data_size|.
332*5a923131SAndroid Build Coastguard Worker bool ReadExtents(const std::string& path,
333*5a923131SAndroid Build Coastguard Worker                  const std::vector<Extent>& extents,
334*5a923131SAndroid Build Coastguard Worker                  brillo::Blob* out_data,
335*5a923131SAndroid Build Coastguard Worker                  ssize_t out_data_size,
336*5a923131SAndroid Build Coastguard Worker                  size_t block_size);
337*5a923131SAndroid Build Coastguard Worker 
338*5a923131SAndroid Build Coastguard Worker bool ReadExtents(FileDescriptorPtr path,
339*5a923131SAndroid Build Coastguard Worker                  const std::vector<Extent>& extents,
340*5a923131SAndroid Build Coastguard Worker                  brillo::Blob* out_data,
341*5a923131SAndroid Build Coastguard Worker                  ssize_t out_data_size,
342*5a923131SAndroid Build Coastguard Worker                  size_t block_size);
343*5a923131SAndroid Build Coastguard Worker 
344*5a923131SAndroid Build Coastguard Worker bool WriteExtents(const std::string& path,
345*5a923131SAndroid Build Coastguard Worker                   const google::protobuf::RepeatedPtrField<Extent>& extents,
346*5a923131SAndroid Build Coastguard Worker                   const brillo::Blob& data,
347*5a923131SAndroid Build Coastguard Worker                   size_t block_size);
348*5a923131SAndroid Build Coastguard Worker 
ReadExtents(const std::string & path,const std::vector<Extent> & extents,brillo::Blob * out_data,size_t block_size)349*5a923131SAndroid Build Coastguard Worker constexpr bool ReadExtents(const std::string& path,
350*5a923131SAndroid Build Coastguard Worker                            const std::vector<Extent>& extents,
351*5a923131SAndroid Build Coastguard Worker                            brillo::Blob* out_data,
352*5a923131SAndroid Build Coastguard Worker                            size_t block_size) {
353*5a923131SAndroid Build Coastguard Worker   return ReadExtents(path,
354*5a923131SAndroid Build Coastguard Worker                      extents,
355*5a923131SAndroid Build Coastguard Worker                      out_data,
356*5a923131SAndroid Build Coastguard Worker                      utils::BlocksInExtents(extents) * block_size,
357*5a923131SAndroid Build Coastguard Worker                      block_size);
358*5a923131SAndroid Build Coastguard Worker }
359*5a923131SAndroid Build Coastguard Worker 
360*5a923131SAndroid Build Coastguard Worker bool ReadExtents(const std::string& path,
361*5a923131SAndroid Build Coastguard Worker                  const google::protobuf::RepeatedPtrField<Extent>& extents,
362*5a923131SAndroid Build Coastguard Worker                  brillo::Blob* out_data,
363*5a923131SAndroid Build Coastguard Worker                  size_t block_size);
364*5a923131SAndroid Build Coastguard Worker 
365*5a923131SAndroid Build Coastguard Worker bool ReadExtents(FileDescriptorPtr path,
366*5a923131SAndroid Build Coastguard Worker                  const google::protobuf::RepeatedPtrField<Extent>& extents,
367*5a923131SAndroid Build Coastguard Worker                  brillo::Blob* out_data,
368*5a923131SAndroid Build Coastguard Worker                  size_t block_size);
369*5a923131SAndroid Build Coastguard Worker 
370*5a923131SAndroid Build Coastguard Worker // Read the current boot identifier and store it in |boot_id|. This identifier
371*5a923131SAndroid Build Coastguard Worker // is constants during the same boot of the kernel and is regenerated after
372*5a923131SAndroid Build Coastguard Worker // reboot. Returns whether it succeeded getting the boot_id.
373*5a923131SAndroid Build Coastguard Worker bool GetBootId(std::string* boot_id);
374*5a923131SAndroid Build Coastguard Worker 
375*5a923131SAndroid Build Coastguard Worker // Gets a string value from the vpd for a given key using the `vpd_get_value`
376*5a923131SAndroid Build Coastguard Worker // shell command. Returns true on success.
377*5a923131SAndroid Build Coastguard Worker bool GetVpdValue(std::string key, std::string* result);
378*5a923131SAndroid Build Coastguard Worker 
379*5a923131SAndroid Build Coastguard Worker // This function gets the file path of the file pointed to by FileDiscriptor.
380*5a923131SAndroid Build Coastguard Worker std::string GetFilePath(int fd);
381*5a923131SAndroid Build Coastguard Worker 
382*5a923131SAndroid Build Coastguard Worker // Divide |x| by |y| and round up to the nearest integer.
DivRoundUp(uint64_t x,uint64_t y)383*5a923131SAndroid Build Coastguard Worker constexpr uint64_t DivRoundUp(uint64_t x, uint64_t y) {
384*5a923131SAndroid Build Coastguard Worker   return (x + y - 1) / y;
385*5a923131SAndroid Build Coastguard Worker }
386*5a923131SAndroid Build Coastguard Worker 
387*5a923131SAndroid Build Coastguard Worker // Round |x| up to be a multiple of |y|.
RoundUp(uint64_t x,uint64_t y)388*5a923131SAndroid Build Coastguard Worker constexpr uint64_t RoundUp(uint64_t x, uint64_t y) {
389*5a923131SAndroid Build Coastguard Worker   return DivRoundUp(x, y) * y;
390*5a923131SAndroid Build Coastguard Worker }
391*5a923131SAndroid Build Coastguard Worker 
392*5a923131SAndroid Build Coastguard Worker // Returns the integer value of the first section of |version|. E.g. for
393*5a923131SAndroid Build Coastguard Worker //  "10575.39." returns 10575. Returns 0 if |version| is empty, returns -1 if
394*5a923131SAndroid Build Coastguard Worker // first section of |version| is invalid (e.g. not a number).
395*5a923131SAndroid Build Coastguard Worker int VersionPrefix(const std::string& version);
396*5a923131SAndroid Build Coastguard Worker 
397*5a923131SAndroid Build Coastguard Worker // Parses a string in the form high.low, where high and low are 16 bit unsigned
398*5a923131SAndroid Build Coastguard Worker // integers. If there is more than 1 dot, or if either of the two parts are
399*5a923131SAndroid Build Coastguard Worker // not valid 16 bit unsigned numbers, then 0xffff is returned for both.
400*5a923131SAndroid Build Coastguard Worker void ParseRollbackKeyVersion(const std::string& raw_version,
401*5a923131SAndroid Build Coastguard Worker                              uint16_t* high_version,
402*5a923131SAndroid Build Coastguard Worker                              uint16_t* low_version);
403*5a923131SAndroid Build Coastguard Worker 
404*5a923131SAndroid Build Coastguard Worker // Return a string representation of |utime| for log file names.
405*5a923131SAndroid Build Coastguard Worker std::string GetTimeAsString(time_t utime);
406*5a923131SAndroid Build Coastguard Worker // Returns the string format of the hashed |str_to_convert| that can be used
407*5a923131SAndroid Build Coastguard Worker // with |Excluder| as the exclusion name.
408*5a923131SAndroid Build Coastguard Worker std::string GetExclusionName(const std::string& str_to_convert);
409*5a923131SAndroid Build Coastguard Worker 
410*5a923131SAndroid Build Coastguard Worker // Parse `old_version` and `new_version` as integer timestamps and
411*5a923131SAndroid Build Coastguard Worker // Return kSuccess if `new_version` is larger/newer.
412*5a923131SAndroid Build Coastguard Worker // Return kSuccess if either one is empty.
413*5a923131SAndroid Build Coastguard Worker // Return kError if |old_version| is not empty and not an integer.
414*5a923131SAndroid Build Coastguard Worker // Return kDownloadManifestParseError if |new_version| is not empty and not an
415*5a923131SAndroid Build Coastguard Worker // integer.
416*5a923131SAndroid Build Coastguard Worker // Return kPayloadTimestampError if both are integers but |new_version| <
417*5a923131SAndroid Build Coastguard Worker // |old_version|.
418*5a923131SAndroid Build Coastguard Worker ErrorCode IsTimestampNewer(const std::string_view old_version,
419*5a923131SAndroid Build Coastguard Worker                            const std::string_view new_version);
420*5a923131SAndroid Build Coastguard Worker 
421*5a923131SAndroid Build Coastguard Worker std::unique_ptr<android::base::MappedFile> GetReadonlyZeroBlock(size_t size);
422*5a923131SAndroid Build Coastguard Worker 
423*5a923131SAndroid Build Coastguard Worker std::string_view GetReadonlyZeroString(size_t size);
424*5a923131SAndroid Build Coastguard Worker 
425*5a923131SAndroid Build Coastguard Worker }  // namespace utils
426*5a923131SAndroid Build Coastguard Worker 
427*5a923131SAndroid Build Coastguard Worker // Utility class to close a file descriptor
428*5a923131SAndroid Build Coastguard Worker class ScopedFdCloser {
429*5a923131SAndroid Build Coastguard Worker  public:
ScopedFdCloser(int * fd)430*5a923131SAndroid Build Coastguard Worker   explicit ScopedFdCloser(int* fd) : fd_(fd) {}
~ScopedFdCloser()431*5a923131SAndroid Build Coastguard Worker   ~ScopedFdCloser() {
432*5a923131SAndroid Build Coastguard Worker     if (should_close_ && fd_ && (*fd_ >= 0) && !IGNORE_EINTR(close(*fd_)))
433*5a923131SAndroid Build Coastguard Worker       *fd_ = -1;
434*5a923131SAndroid Build Coastguard Worker   }
set_should_close(bool should_close)435*5a923131SAndroid Build Coastguard Worker   void set_should_close(bool should_close) { should_close_ = should_close; }
436*5a923131SAndroid Build Coastguard Worker 
437*5a923131SAndroid Build Coastguard Worker  private:
438*5a923131SAndroid Build Coastguard Worker   int* fd_;
439*5a923131SAndroid Build Coastguard Worker   bool should_close_ = true;
440*5a923131SAndroid Build Coastguard Worker   DISALLOW_COPY_AND_ASSIGN(ScopedFdCloser);
441*5a923131SAndroid Build Coastguard Worker };
442*5a923131SAndroid Build Coastguard Worker 
443*5a923131SAndroid Build Coastguard Worker // Utility class to delete a file when it goes out of scope.
444*5a923131SAndroid Build Coastguard Worker class ScopedPathUnlinker {
445*5a923131SAndroid Build Coastguard Worker  public:
ScopedPathUnlinker(const std::string & path)446*5a923131SAndroid Build Coastguard Worker   explicit ScopedPathUnlinker(const std::string& path)
447*5a923131SAndroid Build Coastguard Worker       : path_(path), should_remove_(true) {}
~ScopedPathUnlinker()448*5a923131SAndroid Build Coastguard Worker   ~ScopedPathUnlinker() {
449*5a923131SAndroid Build Coastguard Worker     if (should_remove_ && unlink(path_.c_str()) < 0) {
450*5a923131SAndroid Build Coastguard Worker       PLOG(ERROR) << "Unable to unlink path " << path_;
451*5a923131SAndroid Build Coastguard Worker     }
452*5a923131SAndroid Build Coastguard Worker   }
set_should_remove(bool should_remove)453*5a923131SAndroid Build Coastguard Worker   void set_should_remove(bool should_remove) { should_remove_ = should_remove; }
454*5a923131SAndroid Build Coastguard Worker 
455*5a923131SAndroid Build Coastguard Worker  private:
456*5a923131SAndroid Build Coastguard Worker   const std::string path_;
457*5a923131SAndroid Build Coastguard Worker   bool should_remove_;
458*5a923131SAndroid Build Coastguard Worker   DISALLOW_COPY_AND_ASSIGN(ScopedPathUnlinker);
459*5a923131SAndroid Build Coastguard Worker };
460*5a923131SAndroid Build Coastguard Worker 
461*5a923131SAndroid Build Coastguard Worker class ScopedTempFile {
462*5a923131SAndroid Build Coastguard Worker  public:
ScopedTempFile()463*5a923131SAndroid Build Coastguard Worker   ScopedTempFile() : ScopedTempFile("update_engine_temp.XXXXXX") {}
464*5a923131SAndroid Build Coastguard Worker 
465*5a923131SAndroid Build Coastguard Worker   // If |open_fd| is true, a writable file descriptor will be opened for this
466*5a923131SAndroid Build Coastguard Worker   // file.
467*5a923131SAndroid Build Coastguard Worker   // If |truncate_size| is non-zero, truncate file to that size on creation.
468*5a923131SAndroid Build Coastguard Worker   explicit ScopedTempFile(const std::string& pattern,
469*5a923131SAndroid Build Coastguard Worker                           bool open_fd = false,
470*5a923131SAndroid Build Coastguard Worker                           size_t truncate_size = 0) {
471*5a923131SAndroid Build Coastguard Worker     CHECK(utils::MakeTempFile(pattern, &path_, open_fd ? &fd_ : nullptr));
472*5a923131SAndroid Build Coastguard Worker     unlinker_.reset(new ScopedPathUnlinker(path_));
473*5a923131SAndroid Build Coastguard Worker     if (open_fd) {
474*5a923131SAndroid Build Coastguard Worker       CHECK_GE(fd_, 0);
475*5a923131SAndroid Build Coastguard Worker       fd_closer_.reset(new ScopedFdCloser(&fd_));
476*5a923131SAndroid Build Coastguard Worker     }
477*5a923131SAndroid Build Coastguard Worker     if (truncate_size > 0) {
478*5a923131SAndroid Build Coastguard Worker       CHECK_EQ(0, truncate(path_.c_str(), truncate_size));
479*5a923131SAndroid Build Coastguard Worker     }
480*5a923131SAndroid Build Coastguard Worker   }
481*5a923131SAndroid Build Coastguard Worker   virtual ~ScopedTempFile() = default;
482*5a923131SAndroid Build Coastguard Worker 
path()483*5a923131SAndroid Build Coastguard Worker   const std::string& path() const { return path_; }
fd()484*5a923131SAndroid Build Coastguard Worker   int fd() const {
485*5a923131SAndroid Build Coastguard Worker     CHECK(fd_closer_);
486*5a923131SAndroid Build Coastguard Worker     return fd_;
487*5a923131SAndroid Build Coastguard Worker   }
CloseFd()488*5a923131SAndroid Build Coastguard Worker   void CloseFd() {
489*5a923131SAndroid Build Coastguard Worker     CHECK(fd_closer_);
490*5a923131SAndroid Build Coastguard Worker     fd_closer_.reset();
491*5a923131SAndroid Build Coastguard Worker   }
492*5a923131SAndroid Build Coastguard Worker 
493*5a923131SAndroid Build Coastguard Worker  private:
494*5a923131SAndroid Build Coastguard Worker   std::string path_;
495*5a923131SAndroid Build Coastguard Worker   std::unique_ptr<ScopedPathUnlinker> unlinker_;
496*5a923131SAndroid Build Coastguard Worker 
497*5a923131SAndroid Build Coastguard Worker   int fd_{-1};
498*5a923131SAndroid Build Coastguard Worker   std::unique_ptr<ScopedFdCloser> fd_closer_;
499*5a923131SAndroid Build Coastguard Worker 
500*5a923131SAndroid Build Coastguard Worker   DISALLOW_COPY_AND_ASSIGN(ScopedTempFile);
501*5a923131SAndroid Build Coastguard Worker };
502*5a923131SAndroid Build Coastguard Worker 
503*5a923131SAndroid Build Coastguard Worker // A little object to call ActionComplete on the ActionProcessor when
504*5a923131SAndroid Build Coastguard Worker // it's destructed.
505*5a923131SAndroid Build Coastguard Worker class ScopedActionCompleter {
506*5a923131SAndroid Build Coastguard Worker  public:
ScopedActionCompleter(ActionProcessor * processor,AbstractAction * action)507*5a923131SAndroid Build Coastguard Worker   explicit ScopedActionCompleter(ActionProcessor* processor,
508*5a923131SAndroid Build Coastguard Worker                                  AbstractAction* action)
509*5a923131SAndroid Build Coastguard Worker       : processor_(processor),
510*5a923131SAndroid Build Coastguard Worker         action_(action),
511*5a923131SAndroid Build Coastguard Worker         code_(ErrorCode::kError),
512*5a923131SAndroid Build Coastguard Worker         should_complete_(true) {
513*5a923131SAndroid Build Coastguard Worker     CHECK(processor_);
514*5a923131SAndroid Build Coastguard Worker   }
~ScopedActionCompleter()515*5a923131SAndroid Build Coastguard Worker   ~ScopedActionCompleter() {
516*5a923131SAndroid Build Coastguard Worker     if (should_complete_)
517*5a923131SAndroid Build Coastguard Worker       processor_->ActionComplete(action_, code_);
518*5a923131SAndroid Build Coastguard Worker   }
set_code(ErrorCode code)519*5a923131SAndroid Build Coastguard Worker   void set_code(ErrorCode code) { code_ = code; }
set_should_complete(bool should_complete)520*5a923131SAndroid Build Coastguard Worker   void set_should_complete(bool should_complete) {
521*5a923131SAndroid Build Coastguard Worker     should_complete_ = should_complete;
522*5a923131SAndroid Build Coastguard Worker   }
get_code()523*5a923131SAndroid Build Coastguard Worker   ErrorCode get_code() const { return code_; }
524*5a923131SAndroid Build Coastguard Worker 
525*5a923131SAndroid Build Coastguard Worker  private:
526*5a923131SAndroid Build Coastguard Worker   ActionProcessor* processor_;
527*5a923131SAndroid Build Coastguard Worker   AbstractAction* action_;
528*5a923131SAndroid Build Coastguard Worker   ErrorCode code_;
529*5a923131SAndroid Build Coastguard Worker   bool should_complete_;
530*5a923131SAndroid Build Coastguard Worker   DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
531*5a923131SAndroid Build Coastguard Worker };
532*5a923131SAndroid Build Coastguard Worker 
533*5a923131SAndroid Build Coastguard Worker // Simple wrapper for creating a slice of some container,
534*5a923131SAndroid Build Coastguard Worker // similar to string_view but for other containers.
535*5a923131SAndroid Build Coastguard Worker template <typename T>
536*5a923131SAndroid Build Coastguard Worker struct Range {
RangeRange537*5a923131SAndroid Build Coastguard Worker   Range(T t1, T t2) : t1_(t1), t2_(t2) {}
beginRange538*5a923131SAndroid Build Coastguard Worker   constexpr auto begin() const noexcept { return t1_; }
endRange539*5a923131SAndroid Build Coastguard Worker   constexpr auto end() const noexcept { return t2_; }
540*5a923131SAndroid Build Coastguard Worker   T t1_;
541*5a923131SAndroid Build Coastguard Worker   T t2_;
542*5a923131SAndroid Build Coastguard Worker };
543*5a923131SAndroid Build Coastguard Worker 
544*5a923131SAndroid Build Coastguard Worker std::string HexEncode(const brillo::Blob& blob) noexcept;
545*5a923131SAndroid Build Coastguard Worker std::string HexEncode(const std::string_view blob) noexcept;
546*5a923131SAndroid Build Coastguard Worker 
547*5a923131SAndroid Build Coastguard Worker template <size_t kSize>
HexEncode(const std::array<uint8_t,kSize> blob)548*5a923131SAndroid Build Coastguard Worker std::string HexEncode(const std::array<uint8_t, kSize> blob) noexcept {
549*5a923131SAndroid Build Coastguard Worker   return base::HexEncode(blob.data(), blob.size());
550*5a923131SAndroid Build Coastguard Worker }
551*5a923131SAndroid Build Coastguard Worker 
552*5a923131SAndroid Build Coastguard Worker [[nodiscard]] std::string_view ToStringView(
553*5a923131SAndroid Build Coastguard Worker     const std::vector<unsigned char>& blob) noexcept;
554*5a923131SAndroid Build Coastguard Worker 
ToStringView(const std::vector<char> & blob)555*5a923131SAndroid Build Coastguard Worker constexpr std::string_view ToStringView(
556*5a923131SAndroid Build Coastguard Worker     const std::vector<char>& blob) noexcept {
557*5a923131SAndroid Build Coastguard Worker   return std::string_view{blob.data(), blob.size()};
558*5a923131SAndroid Build Coastguard Worker }
559*5a923131SAndroid Build Coastguard Worker 
560*5a923131SAndroid Build Coastguard Worker [[nodiscard]] std::string_view ToStringView(const void* data,
561*5a923131SAndroid Build Coastguard Worker                                             size_t size) noexcept;
562*5a923131SAndroid Build Coastguard Worker 
563*5a923131SAndroid Build Coastguard Worker bool GetTempName(const std::string& path, base::FilePath* template_path);
564*5a923131SAndroid Build Coastguard Worker 
565*5a923131SAndroid Build Coastguard Worker template <typename String>
ToLower(const String & str)566*5a923131SAndroid Build Coastguard Worker std::string ToLower(const String& str) {
567*5a923131SAndroid Build Coastguard Worker   auto copy = std::string(str);
568*5a923131SAndroid Build Coastguard Worker   std::transform(str.begin(), str.end(), copy.begin(), [](unsigned char c) {
569*5a923131SAndroid Build Coastguard Worker     return std::tolower(c);
570*5a923131SAndroid Build Coastguard Worker   });
571*5a923131SAndroid Build Coastguard Worker   return copy;
572*5a923131SAndroid Build Coastguard Worker }
573*5a923131SAndroid Build Coastguard Worker 
574*5a923131SAndroid Build Coastguard Worker }  // namespace chromeos_update_engine
575*5a923131SAndroid Build Coastguard Worker 
576*5a923131SAndroid Build Coastguard Worker #define TEST_AND_RETURN_FALSE_ERRNO(_x)                             \
577*5a923131SAndroid Build Coastguard Worker   do {                                                              \
578*5a923131SAndroid Build Coastguard Worker     bool _success = static_cast<bool>(_x);                          \
579*5a923131SAndroid Build Coastguard Worker     if (!_success) {                                                \
580*5a923131SAndroid Build Coastguard Worker       std::string _msg = android::base::ErrnoNumberAsString(errno); \
581*5a923131SAndroid Build Coastguard Worker       LOG(ERROR) << #_x " failed: " << _msg;                        \
582*5a923131SAndroid Build Coastguard Worker       return false;                                                 \
583*5a923131SAndroid Build Coastguard Worker     }                                                               \
584*5a923131SAndroid Build Coastguard Worker   } while (0)
585*5a923131SAndroid Build Coastguard Worker 
586*5a923131SAndroid Build Coastguard Worker #define TEST_AND_RETURN_FALSE(_x)          \
587*5a923131SAndroid Build Coastguard Worker   do {                                     \
588*5a923131SAndroid Build Coastguard Worker     bool _success = static_cast<bool>(_x); \
589*5a923131SAndroid Build Coastguard Worker     if (!_success) {                       \
590*5a923131SAndroid Build Coastguard Worker       LOG(ERROR) << #_x " failed.";        \
591*5a923131SAndroid Build Coastguard Worker       return false;                        \
592*5a923131SAndroid Build Coastguard Worker     }                                      \
593*5a923131SAndroid Build Coastguard Worker   } while (0)
594*5a923131SAndroid Build Coastguard Worker 
595*5a923131SAndroid Build Coastguard Worker #define TEST_AND_RETURN_ERRNO(_x)                                   \
596*5a923131SAndroid Build Coastguard Worker   do {                                                              \
597*5a923131SAndroid Build Coastguard Worker     bool _success = static_cast<bool>(_x);                          \
598*5a923131SAndroid Build Coastguard Worker     if (!_success) {                                                \
599*5a923131SAndroid Build Coastguard Worker       std::string _msg = android::base::ErrnoNumberAsString(errno); \
600*5a923131SAndroid Build Coastguard Worker       LOG(ERROR) << #_x " failed: " << _msg;                        \
601*5a923131SAndroid Build Coastguard Worker       return;                                                       \
602*5a923131SAndroid Build Coastguard Worker     }                                                               \
603*5a923131SAndroid Build Coastguard Worker   } while (0)
604*5a923131SAndroid Build Coastguard Worker 
605*5a923131SAndroid Build Coastguard Worker #define TEST_AND_RETURN(_x)                \
606*5a923131SAndroid Build Coastguard Worker   do {                                     \
607*5a923131SAndroid Build Coastguard Worker     bool _success = static_cast<bool>(_x); \
608*5a923131SAndroid Build Coastguard Worker     if (!_success) {                       \
609*5a923131SAndroid Build Coastguard Worker       LOG(ERROR) << #_x " failed.";        \
610*5a923131SAndroid Build Coastguard Worker       return;                              \
611*5a923131SAndroid Build Coastguard Worker     }                                      \
612*5a923131SAndroid Build Coastguard Worker   } while (0)
613*5a923131SAndroid Build Coastguard Worker 
614*5a923131SAndroid Build Coastguard Worker #define TEST_AND_RETURN_FALSE_ERRCODE(_x)      \
615*5a923131SAndroid Build Coastguard Worker   do {                                         \
616*5a923131SAndroid Build Coastguard Worker     errcode_t _error = (_x);                   \
617*5a923131SAndroid Build Coastguard Worker     if (_error) {                              \
618*5a923131SAndroid Build Coastguard Worker       errno = _error;                          \
619*5a923131SAndroid Build Coastguard Worker       LOG(ERROR) << #_x " failed: " << _error; \
620*5a923131SAndroid Build Coastguard Worker       return false;                            \
621*5a923131SAndroid Build Coastguard Worker     }                                          \
622*5a923131SAndroid Build Coastguard Worker   } while (0)
623*5a923131SAndroid Build Coastguard Worker 
624*5a923131SAndroid Build Coastguard Worker #define TEST_OP(_x, _y, op)                                                \
625*5a923131SAndroid Build Coastguard Worker   do {                                                                     \
626*5a923131SAndroid Build Coastguard Worker     const auto& x = _x;                                                    \
627*5a923131SAndroid Build Coastguard Worker     const auto& y = _y;                                                    \
628*5a923131SAndroid Build Coastguard Worker     if (!(x op y)) {                                                       \
629*5a923131SAndroid Build Coastguard Worker       LOG(ERROR) << #_x " " #op " " #_y << " failed: " << x << " " #op " " \
630*5a923131SAndroid Build Coastguard Worker                  << y;                                                     \
631*5a923131SAndroid Build Coastguard Worker       return {};                                                           \
632*5a923131SAndroid Build Coastguard Worker     }                                                                      \
633*5a923131SAndroid Build Coastguard Worker   } while (0)
634*5a923131SAndroid Build Coastguard Worker 
635*5a923131SAndroid Build Coastguard Worker #define TEST_EQ(_x, _y) TEST_OP(_x, _y, ==)
636*5a923131SAndroid Build Coastguard Worker #define TEST_NE(_x, _y) TEST_OP(_x, _y, !=)
637*5a923131SAndroid Build Coastguard Worker #define TEST_LE(_x, _y) TEST_OP(_x, _y, <=)
638*5a923131SAndroid Build Coastguard Worker #define TEST_GE(_x, _y) TEST_OP(_x, _y, >=)
639*5a923131SAndroid Build Coastguard Worker #define TEST_LT(_x, _y) TEST_OP(_x, _y, <)
640*5a923131SAndroid Build Coastguard Worker #define TEST_GT(_x, _y) TEST_OP(_x, _y, >)
641*5a923131SAndroid Build Coastguard Worker 
642*5a923131SAndroid Build Coastguard Worker // Macro for running a block of code before function exits.
643*5a923131SAndroid Build Coastguard Worker // Example:
644*5a923131SAndroid Build Coastguard Worker // DEFER {
645*5a923131SAndroid Build Coastguard Worker //     fclose(hc);
646*5a923131SAndroid Build Coastguard Worker //     hc = nullptr;
647*5a923131SAndroid Build Coastguard Worker //   };
648*5a923131SAndroid Build Coastguard Worker // It works by creating a new local variable struct holding the lambda, the
649*5a923131SAndroid Build Coastguard Worker // destructor of that struct will invoke the lambda.
650*5a923131SAndroid Build Coastguard Worker 
651*5a923131SAndroid Build Coastguard Worker constexpr struct {
652*5a923131SAndroid Build Coastguard Worker   template <typename F>
653*5a923131SAndroid Build Coastguard Worker   constexpr auto operator<<(F&& f) const noexcept {
654*5a923131SAndroid Build Coastguard Worker     return android::base::make_scope_guard(std::forward<F>(f));
655*5a923131SAndroid Build Coastguard Worker   }
656*5a923131SAndroid Build Coastguard Worker } deferrer;
657*5a923131SAndroid Build Coastguard Worker 
658*5a923131SAndroid Build Coastguard Worker #define TOKENPASTE1(x, y) x##y
659*5a923131SAndroid Build Coastguard Worker #define TOKENPASTE2(x, y) TOKENPASTE1(x, y)
660*5a923131SAndroid Build Coastguard Worker #define DEFER                                                     \
661*5a923131SAndroid Build Coastguard Worker   auto TOKENPASTE2(_deferred_lambda_call, __COUNTER__) = deferrer \
662*5a923131SAndroid Build Coastguard Worker                                                          << [&]() mutable
663*5a923131SAndroid Build Coastguard Worker 
664*5a923131SAndroid Build Coastguard Worker #endif  // UPDATE_ENGINE_COMMON_UTILS_H_
665