[go: nahoru, domu]

blob: a186a6cc3381e8f97f1707b6d3ffec931a85c2ac [file] [log] [blame]
thestig@chromium.orgb2f28d22012-03-03 01:54:351// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
brettw@chromium.orge3177dd52014-08-13 20:22:145#include "base/files/file_util.h"
initial.commitd7cae122008-07-26 21:49:386
Xiaohan Wangb705a64a2022-01-15 18:31:137#include "build/build_config.h"
8
9#if BUILDFLAG(IS_WIN)
jeremy@chromium.orgc2c998c2009-01-27 19:08:3910#include <io.h>
11#endif
mark@chromium.org836f1342008-10-01 17:40:1312#include <stdio.h>
13
initial.commitd7cae122008-07-26 21:49:3814#include <fstream>
kaliamoorthi@chromium.org0710fdd2014-02-18 16:31:5115#include <limits>
Victor Costanb5a0a97002019-09-08 04:55:1516#include <memory>
Xiaohan Wang12bd22202022-05-19 15:38:0217#include <utility>
Victor Hugo Vianna Silva05f14542021-08-05 16:08:4818#include <vector>
initial.commitd7cae122008-07-26 21:49:3819
Hans Wennborgc3cffa62020-04-27 10:09:1220#include "base/check_op.h"
brettw@chromium.org25a4c1c2013-06-08 04:53:3621#include "base/files/file_enumerator.h"
brettw@chromium.org57999812013-02-24 05:40:5222#include "base/files/file_path.h"
David Sanders83f8ae42022-04-04 23:15:3923#include "base/notreached.h"
Greg Thompson3f7e20f42020-05-02 19:01:1124#include "base/posix/eintr_wrapper.h"
tfarina@chromium.orgeb62f7262013-03-30 14:29:0025#include "base/strings/string_piece.h"
avi@chromium.org251cd6e52013-06-11 13:36:3726#include "base/strings/string_util.h"
27#include "base/strings/stringprintf.h"
avi@chromium.orga4ea1f12013-06-07 18:37:0728#include "base/strings/utf_string_conversions.h"
Xiaohan Wang12bd22202022-05-19 15:38:0229#include "base/task/bind_post_task.h"
Etienne Pierre-Doray1da58592018-09-21 14:47:2030#include "base/threading/scoped_blocking_call.h"
Xiaohan Wang12bd22202022-05-19 15:38:0231#include "base/threading/sequenced_task_runner_handle.h"
avi543540e2015-12-24 05:15:3232#include "build/build_config.h"
estade@chromium.orgb9e04f02008-11-27 04:03:5733
Xiaohan Wangb705a64a2022-01-15 18:31:1334#if BUILDFLAG(IS_WIN)
Bruce Dawson1ad438d2021-07-09 20:10:0335#include <windows.h>
36#endif
37
brettw@chromium.org0408c752013-06-22 22:15:4638namespace base {
brettw@chromium.org04af979a2013-02-16 04:12:2639
Xiaohan Wang5b7ea512022-05-20 14:56:2940#if !BUILDFLAG(IS_WIN)
41
Xiaohan Wang12bd22202022-05-19 15:38:0242namespace {
43
44void RunAndReply(OnceCallback<bool()> action_callback,
45 OnceCallback<void(bool)> reply_callback) {
46 bool result = std::move(action_callback).Run();
47 if (!reply_callback.is_null())
48 std::move(reply_callback).Run(result);
49}
50
51} // namespace
52
Xiaohan Wang12bd22202022-05-19 15:38:0253OnceClosure GetDeleteFileCallback(const FilePath& path,
54 OnceCallback<void(bool)> reply_callback) {
55 return BindOnce(&RunAndReply, BindOnce(&DeleteFile, path),
56 reply_callback.is_null()
57 ? std::move(reply_callback)
58 : BindPostTask(SequencedTaskRunnerHandle::Get(),
59 std::move(reply_callback)));
Lei Zhange3aa0b9a2020-06-11 08:59:2360}
61
Xiaohan Wang12bd22202022-05-19 15:38:0262OnceClosure GetDeletePathRecursivelyCallback(
63 const FilePath& path,
64 OnceCallback<void(bool)> reply_callback) {
65 return BindOnce(&RunAndReply, BindOnce(&DeletePathRecursively, path),
66 reply_callback.is_null()
67 ? std::move(reply_callback)
68 : BindPostTask(SequencedTaskRunnerHandle::Get(),
69 std::move(reply_callback)));
Lei Zhang3190449f2020-06-12 05:14:0470}
71
Xiaohan Wang5b7ea512022-05-20 14:56:2972#endif // !BUILDFLAG(IS_WIN)
73
avi543540e2015-12-24 05:15:3274int64_t ComputeDirectorySize(const FilePath& root_path) {
75 int64_t running_size = 0;
brettw@chromium.org0408c752013-06-22 22:15:4676 FileEnumerator file_iter(root_path, true, FileEnumerator::FILES);
77 while (!file_iter.Next().empty())
78 running_size += file_iter.GetInfo().GetSize();
79 return running_size;
80}
81
brettw@chromium.org5553d5b2013-07-01 23:07:3682bool Move(const FilePath& from_path, const FilePath& to_path) {
83 if (from_path.ReferencesParent() || to_path.ReferencesParent())
84 return false;
brettw@chromium.orgf0ff2ad2013-07-09 17:42:2685 return internal::MoveUnsafe(from_path, to_path);
86}
87
Alexander Bolodurin53bfc89c22020-11-25 22:43:2988bool CopyFileContents(File& infile, File& outfile) {
Xiaohan Wangb705a64a2022-01-15 18:31:1389#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
Brian Geffon591e8f22021-04-08 18:33:2390 bool retry_slow = false;
91 bool res =
92 internal::CopyFileContentsWithSendfile(infile, outfile, retry_slow);
93 if (res || !retry_slow) {
94 return res;
95 }
96 // Any failures which allow retrying using read/write will not have modified
97 // either file offset or size.
98#endif
99
Alexander Bolodurin53bfc89c22020-11-25 22:43:29100 static constexpr size_t kBufferSize = 32768;
101 std::vector<char> buffer(kBufferSize);
102
103 for (;;) {
104 int bytes_read = infile.ReadAtCurrentPos(buffer.data(), buffer.size());
105 if (bytes_read < 0) {
106 return false;
107 }
108 if (bytes_read == 0) {
109 return true;
110 }
111 // Allow for partial writes
112 int bytes_written_per_read = 0;
113 do {
114 int bytes_written_partial = outfile.WriteAtCurrentPos(
115 &buffer[bytes_written_per_read], bytes_read - bytes_written_per_read);
116 if (bytes_written_partial < 0) {
117 return false;
118 }
119
120 bytes_written_per_read += bytes_written_partial;
121 } while (bytes_written_per_read < bytes_read);
122 }
123
124 NOTREACHED();
125 return false;
126}
127
evanm@google.com640517f2008-10-30 23:54:04128bool ContentsEqual(const FilePath& filename1, const FilePath& filename2) {
initial.commitd7cae122008-07-26 21:49:38129 // We open the file in binary format even if they are text files because
130 // we are just comparing that bytes are exactly same in both files and not
131 // doing anything smart with text formatting.
Xiaohan Wangb705a64a2022-01-15 18:31:13132#if BUILDFLAG(IS_WIN)
Jan Wilken Dörrie9bb441d2019-11-01 17:48:40133 std::ifstream file1(filename1.value().c_str(),
erikkay@google.com5af2edb92008-08-08 20:16:08134 std::ios::in | std::ios::binary);
Jan Wilken Dörrie9bb441d2019-11-01 17:48:40135 std::ifstream file2(filename2.value().c_str(),
erikkay@google.com5af2edb92008-08-08 20:16:08136 std::ios::in | std::ios::binary);
Xiaohan Wangb705a64a2022-01-15 18:31:13137#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
jdoerrie983968a2019-01-29 12:54:41138 std::ifstream file1(filename1.value(), std::ios::in | std::ios::binary);
139 std::ifstream file2(filename2.value(), std::ios::in | std::ios::binary);
Xiaohan Wangb705a64a2022-01-15 18:31:13140#endif // BUILDFLAG(IS_WIN)
estade@chromium.orgb9e04f02008-11-27 04:03:57141
initial.commitd7cae122008-07-26 21:49:38142 // Even if both files aren't openable (and thus, in some sense, "equal"),
143 // any unusable file yields a result of "false".
144 if (!file1.is_open() || !file2.is_open())
145 return false;
146
147 const int BUFFER_SIZE = 2056;
148 char buffer1[BUFFER_SIZE], buffer2[BUFFER_SIZE];
149 do {
150 file1.read(buffer1, BUFFER_SIZE);
151 file2.read(buffer2, BUFFER_SIZE);
152
mark@chromium.orgb81637c32009-06-26 21:17:24153 if ((file1.eof() != file2.eof()) ||
initial.commitd7cae122008-07-26 21:49:38154 (file1.gcount() != file2.gcount()) ||
pkasting9cf9b942014-10-01 22:18:43155 (memcmp(buffer1, buffer2, static_cast<size_t>(file1.gcount())))) {
initial.commitd7cae122008-07-26 21:49:38156 file1.close();
157 file2.close();
158 return false;
159 }
mark@chromium.orgb81637c32009-06-26 21:17:24160 } while (!file1.eof() || !file2.eof());
initial.commitd7cae122008-07-26 21:49:38161
162 file1.close();
163 file2.close();
164 return true;
165}
166
mark@chromium.orgb81637c32009-06-26 21:17:24167bool TextContentsEqual(const FilePath& filename1, const FilePath& filename2) {
Xiaohan Wangb705a64a2022-01-15 18:31:13168#if BUILDFLAG(IS_WIN)
Jan Wilken Dörrie9bb441d2019-11-01 17:48:40169 std::ifstream file1(filename1.value().c_str(), std::ios::in);
170 std::ifstream file2(filename2.value().c_str(), std::ios::in);
Xiaohan Wangb705a64a2022-01-15 18:31:13171#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
jdoerrie983968a2019-01-29 12:54:41172 std::ifstream file1(filename1.value(), std::ios::in);
173 std::ifstream file2(filename2.value(), std::ios::in);
Xiaohan Wangb705a64a2022-01-15 18:31:13174#endif // BUILDFLAG(IS_WIN)
mark@chromium.orgb81637c32009-06-26 21:17:24175
176 // Even if both files aren't openable (and thus, in some sense, "equal"),
177 // any unusable file yields a result of "false".
178 if (!file1.is_open() || !file2.is_open())
179 return false;
180
181 do {
182 std::string line1, line2;
183 getline(file1, line1);
184 getline(file2, line2);
185
186 // Check for mismatched EOF states, or any error state.
187 if ((file1.eof() != file2.eof()) ||
188 file1.bad() || file2.bad()) {
189 return false;
190 }
191
192 // Trim all '\r' and '\n' characters from the end of the line.
193 std::string::size_type end1 = line1.find_last_not_of("\r\n");
194 if (end1 == std::string::npos)
195 line1.clear();
196 else if (end1 + 1 < line1.length())
197 line1.erase(end1 + 1);
198
199 std::string::size_type end2 = line2.find_last_not_of("\r\n");
200 if (end2 == std::string::npos)
201 line2.clear();
202 else if (end2 + 1 < line2.length())
203 line2.erase(end2 + 1);
204
205 if (line1 != line2)
206 return false;
207 } while (!file1.eof() || !file2.eof());
208
209 return true;
210}
211
Greg Thompson3f7e20f42020-05-02 19:01:11212bool ReadStreamToString(FILE* stream, std::string* contents) {
213 return ReadStreamToStringWithMaxSize(
214 stream, std::numeric_limits<size_t>::max(), contents);
215}
216
217bool ReadStreamToStringWithMaxSize(FILE* stream,
218 size_t max_size,
219 std::string* contents) {
kaliamoorthi@chromium.org0710fdd2014-02-18 16:31:51220 if (contents)
221 contents->clear();
Abhijith Nair1b5b6ee22021-11-18 21:01:59222 if (!stream)
223 return false;
Greg Thompson3f7e20f42020-05-02 19:01:11224 // Seeking to the beginning is best-effort -- it is expected to fail for
225 // certain non-file stream (e.g., pipes).
226 HANDLE_EINTR(fseek(stream, 0, SEEK_SET));
227
228 // Many files have incorrect size (proc files etc). Hence, the file is read
229 // sequentially as opposed to a one-shot read, using file size as a hint for
230 // chunk size if available.
Mikhail Istomin1ede1552018-05-16 17:40:24231 constexpr int64_t kDefaultChunkSize = 1 << 16;
Greg Thompson3f7e20f42020-05-02 19:01:11232 int64_t chunk_size = kDefaultChunkSize - 1;
Greg Thompson3f7e20f42020-05-02 19:01:11233 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
Xiaohan Wangb705a64a2022-01-15 18:31:13234#if BUILDFLAG(IS_WIN)
Greg Thompson3f7e20f42020-05-02 19:01:11235 BY_HANDLE_FILE_INFORMATION file_info = {};
236 if (::GetFileInformationByHandle(
237 reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stream))),
238 &file_info)) {
239 LARGE_INTEGER size;
240 size.HighPart = file_info.nFileSizeHigh;
241 size.LowPart = file_info.nFileSizeLow;
242 if (size.QuadPart > 0)
243 chunk_size = size.QuadPart;
244 }
Xiaohan Wangb705a64a2022-01-15 18:31:13245#else // BUILDFLAG(IS_WIN)
Anand K Mistry53fa72d2021-07-15 01:15:26246 // In cases where the reported file size is 0, use a smaller chunk size to
247 // minimize memory allocated and cost of string::resize() in case the read
248 // size is small (i.e. proc files). If the file is larger than this, the read
249 // loop will reset |chunk_size| to kDefaultChunkSize.
250 constexpr int64_t kSmallChunkSize = 4096;
251 chunk_size = kSmallChunkSize - 1;
Greg Thompson3f7e20f42020-05-02 19:01:11252 stat_wrapper_t file_info = {};
253 if (!File::Fstat(fileno(stream), &file_info) && file_info.st_size > 0)
254 chunk_size = file_info.st_size;
Xiaohan Wangb705a64a2022-01-15 18:31:13255#endif // BUILDFLAG(IS_WIN)
Mikhail Istomin1ede1552018-05-16 17:40:24256 // We need to attempt to read at EOF for feof flag to be set so here we
257 // use |chunk_size| + 1.
258 chunk_size = std::min<uint64_t>(chunk_size, max_size) + 1;
Mikhail Istomin1ede1552018-05-16 17:40:24259 size_t bytes_read_this_pass;
260 size_t bytes_read_so_far = 0;
261 bool read_status = true;
262 std::string local_contents;
263 local_contents.resize(chunk_size);
kaliamoorthi@chromium.org0710fdd2014-02-18 16:31:51264
Mikhail Istomin1ede1552018-05-16 17:40:24265 while ((bytes_read_this_pass = fread(&local_contents[bytes_read_so_far], 1,
Greg Thompson3f7e20f42020-05-02 19:01:11266 chunk_size, stream)) > 0) {
Mikhail Istomin1ede1552018-05-16 17:40:24267 if ((max_size - bytes_read_so_far) < bytes_read_this_pass) {
268 // Read more than max_size bytes, bail out.
269 bytes_read_so_far = max_size;
kaliamoorthi@chromium.org0710fdd2014-02-18 16:31:51270 read_status = false;
271 break;
272 }
Mikhail Istomin1ede1552018-05-16 17:40:24273 // In case EOF was not reached, iterate again but revert to the default
274 // chunk size.
275 if (bytes_read_so_far == 0)
276 chunk_size = kDefaultChunkSize;
kaliamoorthi@chromium.org0710fdd2014-02-18 16:31:51277
Mikhail Istomin1ede1552018-05-16 17:40:24278 bytes_read_so_far += bytes_read_this_pass;
279 // Last fread syscall (after EOF) can be avoided via feof, which is just a
280 // flag check.
Greg Thompson3f7e20f42020-05-02 19:01:11281 if (feof(stream))
Mikhail Istomin1ede1552018-05-16 17:40:24282 break;
283 local_contents.resize(bytes_read_so_far + chunk_size);
initial.commitd7cae122008-07-26 21:49:38284 }
Greg Thompson3f7e20f42020-05-02 19:01:11285 read_status = read_status && !ferror(stream);
Mikhail Istomin1ede1552018-05-16 17:40:24286 if (contents) {
287 contents->swap(local_contents);
288 contents->resize(bytes_read_so_far);
289 }
initial.commitd7cae122008-07-26 21:49:38290
kaliamoorthi@chromium.org0710fdd2014-02-18 16:31:51291 return read_status;
292}
293
294bool ReadFileToString(const FilePath& path, std::string* contents) {
hashimoto6da2fef2016-02-24 03:39:58295 return ReadFileToStringWithMaxSize(path, contents,
296 std::numeric_limits<size_t>::max());
initial.commitd7cae122008-07-26 21:49:38297}
298
Greg Thompson3f7e20f42020-05-02 19:01:11299bool ReadFileToStringWithMaxSize(const FilePath& path,
300 std::string* contents,
301 size_t max_size) {
302 if (contents)
303 contents->clear();
304 if (path.ReferencesParent())
305 return false;
306 ScopedFILE file_stream(OpenFile(path, "rb"));
307 if (!file_stream)
308 return false;
309 return ReadStreamToStringWithMaxSize(file_stream.get(), max_size, contents);
310}
311
brettw@chromium.orgfb4bcfa32013-12-02 18:55:49312bool IsDirectoryEmpty(const FilePath& dir_path) {
313 FileEnumerator files(dir_path, false,
314 FileEnumerator::FILES | FileEnumerator::DIRECTORIES);
315 if (files.Next().empty())
316 return true;
317 return false;
318}
319
Greg Thompson3f7e20f42020-05-02 19:01:11320bool CreateTemporaryFile(FilePath* path) {
321 FilePath temp_dir;
322 return GetTempDir(&temp_dir) && CreateTemporaryFileInDir(temp_dir, path);
323}
324
Greg Thompsonf75f5fb2020-04-30 08:13:25325ScopedFILE CreateAndOpenTemporaryStream(FilePath* path) {
brettw@chromium.org03d9afc02013-12-03 17:55:52326 FilePath directory;
327 if (!GetTempDir(&directory))
Ivan Kotenkova16212a52017-11-08 12:37:33328 return nullptr;
brettw@chromium.org03d9afc02013-12-03 17:55:52329
Greg Thompsonf75f5fb2020-04-30 08:13:25330 return CreateAndOpenTemporaryStreamInDir(directory, path);
brettw@chromium.org03d9afc02013-12-03 17:55:52331}
332
brettw@chromium.org426d1c92013-12-03 20:08:54333bool CreateDirectory(const FilePath& full_path) {
Ivan Kotenkova16212a52017-11-08 12:37:33334 return CreateDirectoryAndGetError(full_path, nullptr);
brettw@chromium.org426d1c92013-12-03 20:08:54335}
336
avi543540e2015-12-24 05:15:32337bool GetFileSize(const FilePath& file_path, int64_t* file_size) {
rvargas@chromium.org54124ed02014-01-07 10:06:58338 File::Info info;
brettw@chromium.org9eae4e62013-12-04 20:56:49339 if (!GetFileInfo(file_path, &info))
brettw@chromium.org56285702013-12-04 18:22:49340 return false;
341 *file_size = info.size;
342 return true;
343}
344
brettw@chromium.orgc0d508162013-12-04 22:49:00345bool TouchFile(const FilePath& path,
346 const Time& last_accessed,
347 const Time& last_modified) {
Alexei Svitkine670d67ee2021-11-01 21:51:49348 int flags = File::FLAG_OPEN | File::FLAG_WRITE_ATTRIBUTES;
brettw@chromium.orgc0d508162013-12-04 22:49:00349
Xiaohan Wangb705a64a2022-01-15 18:31:13350#if BUILDFLAG(IS_WIN)
brettw@chromium.orgc0d508162013-12-04 22:49:00351 // On Windows, FILE_FLAG_BACKUP_SEMANTICS is needed to open a directory.
352 if (DirectoryExists(path))
Alexei Svitkinec417b2cd2021-10-21 14:22:40353 flags |= File::FLAG_WIN_BACKUP_SEMANTICS;
Xiaohan Wangb705a64a2022-01-15 18:31:13354#elif BUILDFLAG(IS_FUCHSIA)
Wez432ea8d892019-03-31 01:17:08355 // On Fuchsia, we need O_RDONLY for directories, or O_WRONLY for files.
356 // TODO(https://crbug.com/947802): Find a cleaner workaround for this.
357 flags |= (DirectoryExists(path) ? File::FLAG_READ : File::FLAG_WRITE);
358#endif
brettw@chromium.orgc0d508162013-12-04 22:49:00359
rvargas@chromium.org54124ed02014-01-07 10:06:58360 File file(path, flags);
361 if (!file.IsValid())
362 return false;
brettw@chromium.orgc0d508162013-12-04 22:49:00363
rvargas@chromium.org54124ed02014-01-07 10:06:58364 return file.SetTimes(last_accessed, last_modified);
brettw@chromium.orgc0d508162013-12-04 22:49:00365}
366
mark@chromium.org836f1342008-10-01 17:40:13367bool CloseFile(FILE* file) {
Ivan Kotenkova16212a52017-11-08 12:37:33368 if (file == nullptr)
sidchat@google.coma1a19502008-10-21 17:14:45369 return true;
mark@chromium.org836f1342008-10-01 17:40:13370 return fclose(file) == 0;
371}
372
jeremy@chromium.orgc2c998c2009-01-27 19:08:39373bool TruncateFile(FILE* file) {
Ivan Kotenkova16212a52017-11-08 12:37:33374 if (file == nullptr)
jeremy@chromium.orgc2c998c2009-01-27 19:08:39375 return false;
376 long current_offset = ftell(file);
377 if (current_offset == -1)
378 return false;
Xiaohan Wangb705a64a2022-01-15 18:31:13379#if BUILDFLAG(IS_WIN)
jeremy@chromium.orgc2c998c2009-01-27 19:08:39380 int fd = _fileno(file);
381 if (_chsize(fd, current_offset) != 0)
382 return false;
383#else
384 int fd = fileno(file);
385 if (ftruncate(fd, current_offset) != 0)
386 return false;
387#endif
388 return true;
389}
390
Lei Zhangeebbef62020-05-05 20:16:05391bool WriteFile(const FilePath& filename, span<const uint8_t> data) {
392 int size = checked_cast<int>(data.size());
393 return WriteFile(filename, reinterpret_cast<const char*>(data.data()),
394 size) == size;
395}
396
397bool WriteFile(const FilePath& filename, StringPiece data) {
398 int size = checked_cast<int>(data.size());
399 return WriteFile(filename, data.data(), size) == size;
400}
401
Greg Thompsonb4abcb42019-08-23 01:42:56402int GetUniquePathNumber(const FilePath& path) {
403 DCHECK(!path.empty());
404 if (!PathExists(path))
Greg Thompson42373544a2019-08-14 10:11:10405 return 0;
406
407 std::string number;
408 for (int count = 1; count <= kMaxUniqueFiles; ++count) {
409 StringAppendF(&number, " (%d)", count);
Greg Thompsonb4abcb42019-08-23 01:42:56410 if (!PathExists(path.InsertBeforeExtensionASCII(number)))
Greg Thompson42373544a2019-08-14 10:11:10411 return count;
412 number.clear();
jam@chromium.orge285afa2012-01-31 23:16:39413 }
414
415 return -1;
416}
Bruce Longd096e482019-02-28 17:50:00417
418FilePath GetUniquePath(const FilePath& path) {
Greg Thompsonb4abcb42019-08-23 01:42:56419 DCHECK(!path.empty());
420 const int uniquifier = GetUniquePathNumber(path);
421 if (uniquifier > 0)
422 return path.InsertBeforeExtensionASCII(StringPrintf(" (%d)", uniquifier));
Xiaohan Wang12bd22202022-05-19 15:38:02423 return uniquifier == 0 ? path : FilePath();
Bruce Longd096e482019-02-28 17:50:00424}
Victor Costanb5a0a97002019-09-08 04:55:15425
426namespace internal {
427
428bool PreReadFileSlow(const FilePath& file_path, int64_t max_bytes) {
429 DCHECK_GE(max_bytes, 0);
430
431 File file(file_path, File::FLAG_OPEN | File::FLAG_READ |
Alexei Svitkinec417b2cd2021-10-21 14:22:40432 File::FLAG_WIN_SEQUENTIAL_SCAN |
433 File::FLAG_WIN_SHARE_DELETE);
Victor Costanb5a0a97002019-09-08 04:55:15434 if (!file.IsValid())
435 return false;
436
437 constexpr int kBufferSize = 1024 * 1024;
438 // Ensures the buffer is deallocated at function exit.
439 std::unique_ptr<char[]> buffer_deleter(new char[kBufferSize]);
440 char* const buffer = buffer_deleter.get();
441
442 while (max_bytes > 0) {
443 // The static_cast<int> is safe because kBufferSize is int, and both values
444 // are non-negative. So, the minimum is guaranteed to fit in int.
445 const int read_size =
446 static_cast<int>(std::min<int64_t>(max_bytes, kBufferSize));
447 DCHECK_GE(read_size, 0);
448 DCHECK_LE(read_size, kBufferSize);
449
450 const int read_bytes = file.ReadAtCurrentPos(buffer, read_size);
451 if (read_bytes < 0)
452 return false;
453 if (read_bytes == 0)
454 break;
455
456 max_bytes -= read_bytes;
457 }
458
459 return true;
460}
461
462} // namespace internal
463
brettw@chromium.orga26f4ae2014-03-13 17:26:21464} // namespace base