• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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  */
16 
17 #include <sys/stat.h>
18 
19 #include "perfetto/base/file_utils.h"
20 
21 #include "perfetto/base/logging.h"
22 #include "perfetto/base/scoped_file.h"
23 
24 namespace perfetto {
25 namespace base {
26 namespace {
27 constexpr size_t kBufSize = 2048;
28 }
29 
ReadFile(const std::string & path,std::string * out)30 bool ReadFile(const std::string& path, std::string* out) {
31   // Do not override existing data in string.
32   size_t i = out->size();
33 
34   base::ScopedFile fd = base::OpenFile(path.c_str(), O_RDONLY);
35   if (!fd)
36     return false;
37 
38   struct stat buf {};
39   if (fstat(*fd, &buf) != -1) {
40     if (buf.st_size > 0)
41       out->resize(i + static_cast<size_t>(buf.st_size));
42   }
43 
44   ssize_t bytes_read;
45   for (;;) {
46     if (out->size() < i + kBufSize)
47       out->resize(out->size() + kBufSize);
48 
49     bytes_read = PERFETTO_EINTR(read(fd.get(), &((*out)[i]), kBufSize));
50     if (bytes_read > 0) {
51       i += static_cast<size_t>(bytes_read);
52     } else {
53       out->resize(i);
54       return bytes_read == 0;
55     }
56   }
57 }
58 
59 }  // namespace base
60 }  // namespace perfetto
61