blob: 088937dd47f7c92857cc6d6767b077518ae2428f [file] [log] [blame]
Florian Mayer74b73a92018-03-09 17:37:13 +00001/*
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
24namespace perfetto {
25namespace base {
26namespace {
Florian Mayerdbd08782018-03-21 14:07:51 +000027constexpr size_t kBufSize = 2048;
Florian Mayer74b73a92018-03-09 17:37:13 +000028}
29
30bool 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);
Primiano Tucci139de772018-03-13 05:52:10 +000035 if (!fd)
Florian Mayer74b73a92018-03-09 17:37:13 +000036 return false;
Florian Mayer74b73a92018-03-09 17:37:13 +000037
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