blob: d43c5995901e85215303fcc566a379fae41c8995 [file] [log] [blame]
[email protected]e3177dd52014-08-13 20:22:141// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This file contains utility functions for dealing with the local
6// filesystem.
7
8#ifndef BASE_FILES_FILE_UTIL_H_
9#define BASE_FILES_FILE_UTIL_H_
10
avi543540e2015-12-24 05:15:3211#include <stddef.h>
12#include <stdint.h>
13#include <stdio.h>
14
Victor Costanb5a0a97002019-09-08 04:55:1515#include <limits>
avi543540e2015-12-24 05:15:3216#include <set>
17#include <string>
18#include <vector>
19
20#include "base/base_export.h"
Lei Zhange3aa0b9a2020-06-11 08:59:2321#include "base/callback_forward.h"
Lei Zhangeebbef62020-05-05 20:16:0522#include "base/containers/span.h"
avi543540e2015-12-24 05:15:3223#include "base/files/file.h"
24#include "base/files/file_path.h"
Greg Thompsonf75f5fb2020-04-30 08:13:2525#include "base/files/scoped_file.h"
[email protected]e3177dd52014-08-13 20:22:1426#include "build/build_config.h"
27
28#if defined(OS_WIN)
Bruce Dawsonbfdc3fd2018-01-03 20:32:3629#include "base/win/windows_types.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3930#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Nico Weber4e8fd4e2021-07-22 07:27:2831#include <sys/stat.h>
32#include <unistd.h>
[email protected]e3177dd52014-08-13 20:22:1433#include "base/file_descriptor_posix.h"
[email protected]e3177dd52014-08-13 20:22:1434#include "base/posix/eintr_wrapper.h"
35#endif
36
37namespace base {
38
thomasanderson1929bb22016-06-24 02:01:0039class Environment;
[email protected]e3177dd52014-08-13 20:22:1440class Time;
41
42//-----------------------------------------------------------------------------
43// Functions that involve filesystem access or modification:
44
45// Returns an absolute version of a relative path. Returns an empty path on
46// error. On POSIX, this function fails if the path does not exist. This
47// function can result in I/O so it can be slow.
48BASE_EXPORT FilePath MakeAbsoluteFilePath(const FilePath& input);
49
50// Returns the total number of bytes used by all the files under |root_path|.
51// If the path does not exist the function returns 0.
52//
53// This function is implemented using the FileEnumerator class so it is not
54// particularly speedy in any platform.
avi543540e2015-12-24 05:15:3255BASE_EXPORT int64_t ComputeDirectorySize(const FilePath& root_path);
[email protected]e3177dd52014-08-13 20:22:1456
57// Deletes the given path, whether it's a file or a directory.
Lei Zhangf96963752020-06-18 20:34:1058// If it's a directory, it's perfectly happy to delete all of the directory's
59// contents, but it will not recursively delete subdirectories and their
60// contents.
61// Returns true if successful, false otherwise. It is considered successful to
62// attempt to delete a file that does not exist.
[email protected]e3177dd52014-08-13 20:22:1463//
Lei Zhangaeb72b52019-10-14 22:39:4064// In POSIX environment and if |path| is a symbolic link, this deletes only
[email protected]e3177dd52014-08-13 20:22:1465// the symlink. (even if the symlink points to a non-existent file)
Lei Zhangf96963752020-06-18 20:34:1066BASE_EXPORT bool DeleteFile(const FilePath& path);
[email protected]e3177dd52014-08-13 20:22:1467
Lei Zhangaeb72b52019-10-14 22:39:4068// Deletes the given path, whether it's a file or a directory.
69// If it's a directory, it's perfectly happy to delete all of the
70// directory's contents, including subdirectories and their contents.
71// Returns true if successful, false otherwise. It is considered successful
72// to attempt to delete a file that does not exist.
73//
74// In POSIX environment and if |path| is a symbolic link, this deletes only
75// the symlink. (even if the symlink points to a non-existent file)
76//
77// WARNING: USING THIS EQUIVALENT TO "rm -rf", SO USE WITH CAUTION.
Lei Zhang746ce472020-07-01 04:39:4578BASE_EXPORT bool DeletePathRecursively(const FilePath& path);
Lei Zhangaeb72b52019-10-14 22:39:4079
Lei Zhangf96963752020-06-18 20:34:1080// Simplified way to get a callback to do DeleteFile(path) and ignore the
David Bienvenu2d6563b2021-04-30 21:20:4381// DeleteFile() result. On Windows, this will retry the delete via delayed tasks
82// for up to 2 seconds before giving up, to deal with AV S/W locking the file.
Lei Zhange3aa0b9a2020-06-11 08:59:2383BASE_EXPORT OnceCallback<void(const FilePath&)> GetDeleteFileCallback();
84
Lei Zhang746ce472020-07-01 04:39:4585// Simplified way to get a callback to do DeletePathRecursively(path) and ignore
86// the DeletePathRecursively() result.
Lei Zhang3190449f72020-06-12 05:14:0487BASE_EXPORT OnceCallback<void(const FilePath&)>
88GetDeletePathRecursivelyCallback();
89
[email protected]e3177dd52014-08-13 20:22:1490#if defined(OS_WIN)
91// Schedules to delete the given path, whether it's a file or a directory, until
92// the operating system is restarted.
93// Note:
94// 1) The file/directory to be deleted should exist in a temp folder.
95// 2) The directory to be deleted must be empty.
96BASE_EXPORT bool DeleteFileAfterReboot(const FilePath& path);
97#endif
98
99// Moves the given path, whether it's a file or a directory.
100// If a simple rename is not possible, such as in the case where the paths are
101// on different volumes, this will attempt to copy and delete. Returns
102// true for success.
103// This function fails if either path contains traversal components ('..').
104BASE_EXPORT bool Move(const FilePath& from_path, const FilePath& to_path);
105
106// Renames file |from_path| to |to_path|. Both paths must be on the same
107// volume, or the function will fail. Destination file will be created
108// if it doesn't exist. Prefer this function over Move when dealing with
109// temporary files. On Windows it preserves attributes of the target file.
110// Returns true on success, leaving *error unchanged.
111// Returns false on failure and sets *error appropriately, if it is non-NULL.
112BASE_EXPORT bool ReplaceFile(const FilePath& from_path,
113 const FilePath& to_path,
114 File::Error* error);
115
Lei Zhang6a0e47ca2017-10-02 23:02:16116// Copies a single file. Use CopyDirectory() to copy directories.
[email protected]e3177dd52014-08-13 20:22:14117// This function fails if either path contains traversal components ('..').
Lei Zhang6a0e47ca2017-10-02 23:02:16118// This function also fails if |to_path| is a directory.
[email protected]e3177dd52014-08-13 20:22:14119//
Lei Zhang6a0e47ca2017-10-02 23:02:16120// On POSIX, if |to_path| is a symlink, CopyFile() will follow the symlink. This
121// may have security implications. Use with care.
122//
123// If |to_path| already exists and is a regular file, it will be overwritten,
124// though its permissions will stay the same.
125//
126// If |to_path| does not exist, it will be created. The new file's permissions
127// varies per platform:
128//
129// - This function keeps the metadata on Windows. The read only bit is not kept.
130// - On Mac and iOS, |to_path| retains |from_path|'s permissions, except user
131// read/write permissions are always set.
132// - On Linux and Android, |to_path| has user read/write permissions only. i.e.
133// Always 0600.
134// - On ChromeOS, |to_path| has user read/write permissions and group/others
135// read permissions. i.e. Always 0644.
[email protected]e3177dd52014-08-13 20:22:14136BASE_EXPORT bool CopyFile(const FilePath& from_path, const FilePath& to_path);
137
Alexander Bolodurin53bfc89c22020-11-25 22:43:29138// Copies the contents of one file into another.
139// The files are taken as is: the copy is done starting from the current offset
140// of |infile| until the end of |infile| is reached, into the current offset of
141// |outfile|.
142BASE_EXPORT bool CopyFileContents(File& infile, File& outfile);
143
[email protected]e3177dd52014-08-13 20:22:14144// Copies the given path, and optionally all subdirectories and their contents
145// as well.
146//
147// If there are files existing under to_path, always overwrite. Returns true
148// if successful, false otherwise. Wildcards on the names are not supported.
149//
Eric Carusobca21fc582017-09-28 00:34:34150// This function has the same metadata behavior as CopyFile().
[email protected]e3177dd52014-08-13 20:22:14151//
152// If you only need to copy a file use CopyFile, it's faster.
153BASE_EXPORT bool CopyDirectory(const FilePath& from_path,
154 const FilePath& to_path,
155 bool recursive);
156
Eric Caruso128f0dd2017-12-16 01:32:49157// Like CopyDirectory() except trying to overwrite an existing file will not
158// work and will return false.
159BASE_EXPORT bool CopyDirectoryExcl(const FilePath& from_path,
160 const FilePath& to_path,
161 bool recursive);
162
[email protected]e3177dd52014-08-13 20:22:14163// Returns true if the given path exists on the local filesystem,
164// false otherwise.
165BASE_EXPORT bool PathExists(const FilePath& path);
166
Avi Drissmanb2a8ac9a2020-09-11 18:41:32167// Returns true if the given path is readable by the user, false otherwise.
168BASE_EXPORT bool PathIsReadable(const FilePath& path);
169
[email protected]e3177dd52014-08-13 20:22:14170// Returns true if the given path is writable by the user, false otherwise.
171BASE_EXPORT bool PathIsWritable(const FilePath& path);
172
173// Returns true if the given path exists and is a directory, false otherwise.
174BASE_EXPORT bool DirectoryExists(const FilePath& path);
175
176// Returns true if the contents of the two files given are equal, false
177// otherwise. If either file can't be read, returns false.
178BASE_EXPORT bool ContentsEqual(const FilePath& filename1,
179 const FilePath& filename2);
180
181// Returns true if the contents of the two text files given are equal, false
182// otherwise. This routine treats "\r\n" and "\n" as equivalent.
183BASE_EXPORT bool TextContentsEqual(const FilePath& filename1,
184 const FilePath& filename2);
185
186// Reads the file at |path| into |contents| and returns true on success and
187// false on error. For security reasons, a |path| containing path traversal
188// components ('..') is treated as a read error and |contents| is set to empty.
189// In case of I/O error, |contents| holds the data that could be read from the
190// file before the error occurred.
191// |contents| may be NULL, in which case this function is useful for its side
192// effect of priming the disk cache (could be used for unit tests).
193BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents);
194
195// Reads the file at |path| into |contents| and returns true on success and
196// false on error. For security reasons, a |path| containing path traversal
197// components ('..') is treated as a read error and |contents| is set to empty.
198// In case of I/O error, |contents| holds the data that could be read from the
199// file before the error occurred. When the file size exceeds |max_size|, the
200// function returns false with |contents| holding the file truncated to
201// |max_size|.
202// |contents| may be NULL, in which case this function is useful for its side
203// effect of priming the disk cache (could be used for unit tests).
hashimoto6da2fef2016-02-24 03:39:58204BASE_EXPORT bool ReadFileToStringWithMaxSize(const FilePath& path,
205 std::string* contents,
206 size_t max_size);
[email protected]e3177dd52014-08-13 20:22:14207
Greg Thompson3f7e20f42020-05-02 19:01:11208// As ReadFileToString, but reading from an open stream after seeking to its
209// start (if supported by the stream).
210BASE_EXPORT bool ReadStreamToString(FILE* stream, std::string* contents);
211
212// As ReadFileToStringWithMaxSize, but reading from an open stream after seeking
213// to its start (if supported by the stream).
214BASE_EXPORT bool ReadStreamToStringWithMaxSize(FILE* stream,
215 size_t max_size,
216 std::string* contents);
217
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39218#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:14219
220// Read exactly |bytes| bytes from file descriptor |fd|, storing the result
221// in |buffer|. This function is protected against EINTR and partial reads.
222// Returns true iff |bytes| bytes have been successfully read from |fd|.
223BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes);
224
Greg Thompsonf75f5fb2020-04-30 08:13:25225// Performs the same function as CreateAndOpenTemporaryStreamInDir(), but
226// returns the file-descriptor wrapped in a ScopedFD, rather than the stream
227// wrapped in a ScopedFILE.
Lei Zhangd22c9732019-08-02 16:31:38228BASE_EXPORT ScopedFD CreateAndOpenFdForTemporaryFileInDir(const FilePath& dir,
229 FilePath* path);
Wez45a7b302018-02-22 22:42:39230
Lei Zhangd22c9732019-08-02 16:31:38231#endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39232
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18233#if defined(OS_POSIX)
Kevin Marshalla9f05ec2017-07-14 02:10:05234
Brian Geffon49ddbf02020-06-19 22:57:56235// ReadFileToStringNonBlocking is identical to ReadFileToString except it
236// guarantees that it will not block. This guarantee is provided on POSIX by
237// opening the file as O_NONBLOCK. This variant should only be used on files
238// which are guaranteed not to block (such as kernel files). Or in situations
239// where a partial read would be acceptable because the backing store returned
240// EWOULDBLOCK.
241BASE_EXPORT bool ReadFileToStringNonBlocking(const base::FilePath& file,
242 std::string* ret);
243
[email protected]e3177dd52014-08-13 20:22:14244// Creates a symbolic link at |symlink| pointing to |target|. Returns
245// false on failure.
246BASE_EXPORT bool CreateSymbolicLink(const FilePath& target,
247 const FilePath& symlink);
248
249// Reads the given |symlink| and returns where it points to in |target|.
250// Returns false upon failure.
251BASE_EXPORT bool ReadSymbolicLink(const FilePath& symlink, FilePath* target);
252
253// Bits and masks of the file permission.
254enum FilePermissionBits {
255 FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO,
256 FILE_PERMISSION_USER_MASK = S_IRWXU,
257 FILE_PERMISSION_GROUP_MASK = S_IRWXG,
258 FILE_PERMISSION_OTHERS_MASK = S_IRWXO,
259
260 FILE_PERMISSION_READ_BY_USER = S_IRUSR,
261 FILE_PERMISSION_WRITE_BY_USER = S_IWUSR,
262 FILE_PERMISSION_EXECUTE_BY_USER = S_IXUSR,
263 FILE_PERMISSION_READ_BY_GROUP = S_IRGRP,
264 FILE_PERMISSION_WRITE_BY_GROUP = S_IWGRP,
265 FILE_PERMISSION_EXECUTE_BY_GROUP = S_IXGRP,
266 FILE_PERMISSION_READ_BY_OTHERS = S_IROTH,
267 FILE_PERMISSION_WRITE_BY_OTHERS = S_IWOTH,
268 FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH,
269};
270
271// Reads the permission of the given |path|, storing the file permission
272// bits in |mode|. If |path| is symbolic link, |mode| is the permission of
273// a file which the symlink points to.
274BASE_EXPORT bool GetPosixFilePermissions(const FilePath& path, int* mode);
275// Sets the permission of the given |path|. If |path| is symbolic link, sets
276// the permission of a file which the symlink points to.
277BASE_EXPORT bool SetPosixFilePermissions(const FilePath& path, int mode);
278
thomasanderson1929bb22016-06-24 02:01:00279// Returns true iff |executable| can be found in any directory specified by the
280// environment variable in |env|.
281BASE_EXPORT bool ExecutableExistsInPath(Environment* env,
282 const FilePath::StringType& executable);
283
Sean McAllister39b8d342020-08-25 09:08:32284#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX)
Sergey Volk76166f5b2018-06-15 17:38:02285// Determine if files under a given |path| can be mapped and then mprotect'd
286// PROT_EXEC. This depends on the mount options used for |path|, which vary
287// among different Linux distributions and possibly local configuration. It also
288// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
289// but its kernel allows mprotect with PROT_EXEC anyway.
290BASE_EXPORT bool IsPathExecutable(const FilePath& path);
Sean McAllister39b8d342020-08-25 09:08:32291#endif // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX)
Sergey Volk76166f5b2018-06-15 17:38:02292
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18293#endif // OS_POSIX
[email protected]e3177dd52014-08-13 20:22:14294
295// Returns true if the given directory is empty
296BASE_EXPORT bool IsDirectoryEmpty(const FilePath& dir_path);
297
298// Get the temporary directory provided by the system.
299//
300// WARNING: In general, you should use CreateTemporaryFile variants below
301// instead of this function. Those variants will ensure that the proper
302// permissions are set so that other users on the system can't edit them while
303// they're open (which can lead to security issues).
304BASE_EXPORT bool GetTempDir(FilePath* path);
305
306// Get the home directory. This is more complicated than just getenv("HOME")
307// as it knows to fall back on getpwent() etc.
308//
309// You should not generally call this directly. Instead use DIR_HOME with the
310// path service which will use this function but cache the value.
311// Path service may also override DIR_HOME.
312BASE_EXPORT FilePath GetHomeDir();
313
Greg Thompson3f7e20f42020-05-02 19:01:11314// Returns a new temporary file in |dir| with a unique name. The file is opened
315// for exclusive read, write, and delete access (note: exclusivity is unique to
316// Windows). On Windows, the returned file supports File::DeleteOnClose.
317// On success, |temp_file| is populated with the full path to the created file.
318BASE_EXPORT File CreateAndOpenTemporaryFileInDir(const FilePath& dir,
319 FilePath* temp_file);
320
[email protected]e3177dd52014-08-13 20:22:14321// Creates a temporary file. The full path is placed in |path|, and the
322// function returns true if was successful in creating the file. The file will
323// be empty and all handles closed after this function returns.
324BASE_EXPORT bool CreateTemporaryFile(FilePath* path);
325
326// Same as CreateTemporaryFile but the file is created in |dir|.
327BASE_EXPORT bool CreateTemporaryFileInDir(const FilePath& dir,
328 FilePath* temp_file);
329
Aidan Wolter3fab2a22020-12-02 20:24:35330// Returns the file name for a temporary file by using a platform-specific
331// naming scheme that incorporates |identifier|.
332BASE_EXPORT FilePath
333FormatTemporaryFileName(FilePath::StringPieceType identifier);
334
Greg Thompson3f7e20f42020-05-02 19:01:11335// Create and open a temporary file stream for exclusive read, write, and delete
336// access (note: exclusivity is unique to Windows). The full path is placed in
337// |path|. Returns the opened file stream, or null in case of error.
Greg Thompsonf75f5fb2020-04-30 08:13:25338BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStream(FilePath* path);
[email protected]e3177dd52014-08-13 20:22:14339
Greg Thompsonf75f5fb2020-04-30 08:13:25340// Similar to CreateAndOpenTemporaryStream, but the file is created in |dir|.
341BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStreamInDir(const FilePath& dir,
342 FilePath* path);
[email protected]e3177dd52014-08-13 20:22:14343
Lei Zhang2a55b442021-04-23 19:26:46344// Do NOT USE in new code. Use ScopedTempDir instead.
345// TODO(crbug.com/561597) Remove existing usage and make this an implementation
346// detail inside ScopedTempDir.
347//
[email protected]e3177dd52014-08-13 20:22:14348// Create a new directory. If prefix is provided, the new directory name is in
349// the format of prefixyyyy.
350// NOTE: prefix is ignored in the POSIX implementation.
351// If success, return true and output the full path of the directory created.
352BASE_EXPORT bool CreateNewTempDirectory(const FilePath::StringType& prefix,
353 FilePath* new_temp_path);
354
355// Create a directory within another directory.
356// Extra characters will be appended to |prefix| to ensure that the
357// new directory does not have the same name as an existing directory.
358BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir,
359 const FilePath::StringType& prefix,
360 FilePath* new_dir);
361
362// Creates a directory, as well as creating any parent directories, if they
363// don't exist. Returns 'true' on successful creation, or if the directory
364// already exists. The directory is only readable by the current user.
365// Returns true on success, leaving *error unchanged.
366// Returns false on failure and sets *error appropriately, if it is non-NULL.
367BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path,
368 File::Error* error);
369
370// Backward-compatible convenience method for the above.
371BASE_EXPORT bool CreateDirectory(const FilePath& full_path);
372
373// Returns the file size. Returns true on success.
avi543540e2015-12-24 05:15:32374BASE_EXPORT bool GetFileSize(const FilePath& file_path, int64_t* file_size);
[email protected]e3177dd52014-08-13 20:22:14375
376// Sets |real_path| to |path| with symbolic links and junctions expanded.
377// On windows, make sure the path starts with a lettered drive.
378// |path| must reference a file. Function will fail if |path| points to
379// a directory or to a nonexistent path. On windows, this function will
Alex Gough84ee78c2019-06-06 22:46:23380// fail if |real_path| would be longer than MAX_PATH characters.
[email protected]e3177dd52014-08-13 20:22:14381BASE_EXPORT bool NormalizeFilePath(const FilePath& path, FilePath* real_path);
382
383#if defined(OS_WIN)
384
385// Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
386// return in |drive_letter_path| the equivalent path that starts with
387// a drive letter ("C:\..."). Return false if no such path exists.
388BASE_EXPORT bool DevicePathToDriveLetterPath(const FilePath& device_path,
389 FilePath* drive_letter_path);
390
Bruce Longc343f7e2019-05-11 02:20:12391// Method that wraps the win32 GetLongPathName API, normalizing the specified
392// path to its long form. An example where this is needed is when comparing
393// temp file paths. If a username isn't a valid 8.3 short file name (even just a
394// lengthy name like "user with long name"), Windows will set the TMP and TEMP
395// environment variables to be 8.3 paths. ::GetTempPath (called in
396// base::GetTempDir) just uses the value specified by TMP or TEMP, and so can
397// return a short path. Returns an empty path on error.
398BASE_EXPORT FilePath MakeLongFilePath(const FilePath& input);
David Bienvenuf863412f2019-12-10 21:55:16399
400// Creates a hard link named |to_file| to the file |from_file|. Both paths
401// must be on the same volume, and |from_file| may not name a directory.
402// Returns true if the hard link is created, false if it fails.
403BASE_EXPORT bool CreateWinHardLink(const FilePath& to_file,
404 const FilePath& from_file);
[email protected]e3177dd52014-08-13 20:22:14405#endif
406
407// This function will return if the given file is a symlink or not.
408BASE_EXPORT bool IsLink(const FilePath& file_path);
409
410// Returns information about the given file path.
411BASE_EXPORT bool GetFileInfo(const FilePath& file_path, File::Info* info);
412
413// Sets the time of the last access and the time of the last modification.
414BASE_EXPORT bool TouchFile(const FilePath& path,
415 const Time& last_accessed,
416 const Time& last_modified);
417
grtd0bc44f2017-02-13 17:52:17418// Wrapper for fopen-like calls. Returns non-NULL FILE* on success. The
419// underlying file descriptor (POSIX) or handle (Windows) is unconditionally
420// configured to not be propagated to child processes.
[email protected]e3177dd52014-08-13 20:22:14421BASE_EXPORT FILE* OpenFile(const FilePath& filename, const char* mode);
422
423// Closes file opened by OpenFile. Returns true on success.
424BASE_EXPORT bool CloseFile(FILE* file);
425
426// Associates a standard FILE stream with an existing File. Note that this
427// functions take ownership of the existing File.
428BASE_EXPORT FILE* FileToFILE(File file, const char* mode);
429
Greg Thompson3f7e20f42020-05-02 19:01:11430// Returns a new handle to the file underlying |file_stream|.
431BASE_EXPORT File FILEToFile(FILE* file_stream);
432
[email protected]e3177dd52014-08-13 20:22:14433// Truncates an open file to end at the location of the current file pointer.
434// This is a cross-platform analog to Windows' SetEndOfFile() function.
435BASE_EXPORT bool TruncateFile(FILE* file);
436
437// Reads at most the given number of bytes from the file into the buffer.
438// Returns the number of read bytes, or -1 on error.
439BASE_EXPORT int ReadFile(const FilePath& filename, char* data, int max_size);
440
441// Writes the given buffer into the file, overwriting any data that was
442// previously there. Returns the number of bytes written, or -1 on error.
Andrew091a47b12019-12-12 00:24:00443// If file doesn't exist, it gets created with read/write permissions for all.
Lei Zhangeebbef62020-05-05 20:16:05444// Note that the other variants of WriteFile() below may be easier to use.
[email protected]e3177dd52014-08-13 20:22:14445BASE_EXPORT int WriteFile(const FilePath& filename, const char* data,
446 int size);
447
Lei Zhangeebbef62020-05-05 20:16:05448// Writes |data| into the file, overwriting any data that was previously there.
449// Returns true if and only if all of |data| was written. If the file does not
450// exist, it gets created with read/write permissions for all.
451BASE_EXPORT bool WriteFile(const FilePath& filename, span<const uint8_t> data);
452
453// Another WriteFile() variant that takes a StringPiece so callers don't have to
454// do manual conversions from a char span to a uint8_t span.
455BASE_EXPORT bool WriteFile(const FilePath& filename, StringPiece data);
456
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39457#if defined(OS_POSIX) || defined(OS_FUCHSIA)
Lei Zhangc9e8a162021-05-14 09:33:52458// Appends |data| to |fd|. Does not close |fd| when done. Returns true iff all
459// of |data| were written to |fd|.
460BASE_EXPORT bool WriteFileDescriptor(int fd, span<const uint8_t> data);
461
462// WriteFileDescriptor() variant that takes a StringPiece so callers don't have
463// to do manual conversions from a char span to a uint8_t span.
464BASE_EXPORT bool WriteFileDescriptor(int fd, StringPiece data);
Alex Ilin925adf02019-04-26 11:03:25465
466// Allocates disk space for the file referred to by |fd| for the byte range
467// starting at |offset| and continuing for |size| bytes. The file size will be
468// changed if |offset|+|len| is greater than the file size. Zeros will fill the
469// new space.
470// After a successful call, subsequent writes into the specified range are
471// guaranteed not to fail because of lack of disk space.
472BASE_EXPORT bool AllocateFileRegion(File* file, int64_t offset, size_t size);
[email protected]e3177dd52014-08-13 20:22:14473#endif
474
Lei Zhangcddf8502021-05-13 08:02:04475// Appends |data| to |filename|. Returns true iff |data| were written to
476// |filename|.
chirantan75ea2fd2014-10-07 23:15:30477BASE_EXPORT bool AppendToFile(const FilePath& filename,
Lei Zhangcddf8502021-05-13 08:02:04478 span<const uint8_t> data);
479
480// AppendToFile() variant that takes a StringPiece so callers don't have to do
481// manual conversions from a char span to a uint8_t span.
482BASE_EXPORT bool AppendToFile(const FilePath& filename, StringPiece data);
[email protected]e3177dd52014-08-13 20:22:14483
484// Gets the current working directory for the process.
485BASE_EXPORT bool GetCurrentDirectory(FilePath* path);
486
487// Sets the current working directory for the process.
488BASE_EXPORT bool SetCurrentDirectory(const FilePath& path);
489
Greg Thompsonb4abcb42019-08-23 01:42:56490// The largest value attempted by GetUniquePath{Number,}.
491enum { kMaxUniqueFiles = 100 };
[email protected]e3177dd52014-08-13 20:22:14492
Greg Thompsonb4abcb42019-08-23 01:42:56493// Returns the number N that makes |path| unique when formatted as " (N)" in a
494// suffix to its basename before any file extension, where N is a number between
495// 1 and 100 (inclusive). Returns 0 if |path| does not exist (meaning that it is
496// unique as-is), or -1 if no such number can be found.
497BASE_EXPORT int GetUniquePathNumber(const FilePath& path);
498
499// Returns |path| if it does not exist. Otherwise, returns |path| with the
500// suffix " (N)" appended to its basename before any file extension, where N is
501// a number between 1 and 100 (inclusive). Returns an empty path if no such
502// number can be found.
Bruce Longd096e4892019-02-28 17:50:00503BASE_EXPORT FilePath GetUniquePath(const FilePath& path);
504
tfarina060df7e2015-12-16 05:15:32505// Sets the given |fd| to non-blocking mode.
506// Returns true if it was able to set it in the non-blocking mode, otherwise
507// false.
508BASE_EXPORT bool SetNonBlocking(int fd);
509
Jesse McKenna768f3be2020-06-26 02:30:26510// Possible results of PreReadFile().
511// These values are persisted to logs. Entries should not be renumbered and
512// numeric values should never be reused.
513enum class PrefetchResultCode {
514 kSuccess = 0,
515 kInvalidFile = 1,
516 kSlowSuccess = 2,
517 kSlowFailed = 3,
518 kMemoryMapFailedSlowUsed = 4,
519 kMemoryMapFailedSlowFailed = 5,
520 kFastFailed = 6,
521 kFastFailedSlowUsed = 7,
522 kFastFailedSlowFailed = 8,
523 kMaxValue = kFastFailedSlowFailed
524};
525
526struct PrefetchResult {
527 bool succeeded() const {
528 return code_ == PrefetchResultCode::kSuccess ||
529 code_ == PrefetchResultCode::kSlowSuccess;
530 }
531 const PrefetchResultCode code_;
532};
533
Victor Costanb5a0a97002019-09-08 04:55:15534// Hints the OS to prefetch the first |max_bytes| of |file_path| into its cache.
535//
536// If called at the appropriate time, this can reduce the latency incurred by
537// feature code that needs to read the file.
538//
539// |max_bytes| specifies how many bytes should be pre-fetched. It may exceed the
540// file's size. Passing in std::numeric_limits<int64_t>::max() is a convenient
541// way to get the entire file pre-fetched.
542//
543// |is_executable| specifies whether the file is to be prefetched as
544// executable code or as data. Windows treats the file backed pages in RAM
545// differently, and specifying the wrong value results in two copies in RAM.
546//
Jesse McKenna768f3be2020-06-26 02:30:26547// Returns a PrefetchResult indicating whether prefetch succeeded, and the type
548// of failure if it did not. A return value of kSuccess does not guarantee that
549// the entire desired range was prefetched.
Victor Costanb5a0a97002019-09-08 04:55:15550//
551// Calling this before using ::LoadLibrary() on Windows is more efficient memory
552// wise, but we must be sure no other threads try to LoadLibrary() the file
553// while we are doing the mapping and prefetching, or the process will get a
554// private copy of the DLL via COW.
Jesse McKenna768f3be2020-06-26 02:30:26555BASE_EXPORT PrefetchResult
556PreReadFile(const FilePath& file_path,
557 bool is_executable,
558 int64_t max_bytes = std::numeric_limits<int64_t>::max());
Victor Costanb5a0a97002019-09-08 04:55:15559
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39560#if defined(OS_POSIX) || defined(OS_FUCHSIA)
Nick Diego Yamane61bf28ba2019-03-19 14:56:37561
562// Creates a pipe. Returns true on success, otherwise false.
563// On success, |read_fd| will be set to the fd of the read side, and
564// |write_fd| will be set to the one of write side. If |non_blocking|
565// is set the pipe will be created with O_NONBLOCK|O_CLOEXEC flags set
566// otherwise flag is set to zero (default).
567BASE_EXPORT bool CreatePipe(ScopedFD* read_fd,
568 ScopedFD* write_fd,
569 bool non_blocking = false);
570
lhchavez80c77bfd2016-10-08 00:50:53571// Creates a non-blocking, close-on-exec pipe.
572// This creates a non-blocking pipe that is not intended to be shared with any
573// child process. This will be done atomically if the operating system supports
574// it. Returns true if it was able to create the pipe, otherwise false.
575BASE_EXPORT bool CreateLocalNonBlockingPipe(int fds[2]);
576
577// Sets the given |fd| to close-on-exec mode.
578// Returns true if it was able to set it in the close-on-exec mode, otherwise
579// false.
580BASE_EXPORT bool SetCloseOnExec(int fd);
581
[email protected]e3177dd52014-08-13 20:22:14582// Test that |path| can only be changed by a given user and members of
583// a given set of groups.
584// Specifically, test that all parts of |path| under (and including) |base|:
585// * Exist.
586// * Are owned by a specific user.
587// * Are not writable by all users.
588// * Are owned by a member of a given set of groups, or are not writable by
589// their group.
590// * Are not symbolic links.
591// This is useful for checking that a config file is administrator-controlled.
592// |base| must contain |path|.
593BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base,
594 const base::FilePath& path,
595 uid_t owner_uid,
596 const std::set<gid_t>& group_gids);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39597#endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:14598
Avi Drissman5b286372020-07-28 21:59:38599#if defined(OS_MAC)
[email protected]e3177dd52014-08-13 20:22:14600// Is |path| writable only by a user with administrator privileges?
601// This function uses Mac OS conventions. The super user is assumed to have
602// uid 0, and the administrator group is assumed to be named "admin".
603// Testing that |path|, and every parent directory including the root of
604// the filesystem, are owned by the superuser, controlled by the group
605// "admin", are not writable by all users, and contain no symbolic links.
606// Will return false if |path| does not exist.
607BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path);
Avi Drissman5b286372020-07-28 21:59:38608#endif // defined(OS_MAC)
[email protected]e3177dd52014-08-13 20:22:14609
610// Returns the maximum length of path component on the volume containing
611// the directory |path|, in the number of FilePath::CharType, or -1 on failure.
612BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path);
613
Sean McAllister39b8d342020-08-25 09:08:32614#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX)
[email protected]e3177dd52014-08-13 20:22:14615// Broad categories of file systems as returned by statfs() on Linux.
616enum FileSystemType {
617 FILE_SYSTEM_UNKNOWN, // statfs failed.
618 FILE_SYSTEM_0, // statfs.f_type == 0 means unknown, may indicate AFS.
619 FILE_SYSTEM_ORDINARY, // on-disk filesystem like ext2
620 FILE_SYSTEM_NFS,
621 FILE_SYSTEM_SMB,
622 FILE_SYSTEM_CODA,
623 FILE_SYSTEM_MEMORY, // in-memory file system
624 FILE_SYSTEM_CGROUP, // cgroup control.
625 FILE_SYSTEM_OTHER, // any other value.
626 FILE_SYSTEM_TYPE_COUNT
627};
628
629// Attempts determine the FileSystemType for |path|.
630// Returns false if |path| doesn't exist.
631BASE_EXPORT bool GetFileSystemType(const FilePath& path, FileSystemType* type);
632#endif
633
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39634#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:14635// Get a temporary directory for shared memory files. The directory may depend
636// on whether the destination is intended for executable files, which in turn
637// depends on how /dev/shmem was mounted. As a result, you must supply whether
638// you intend to create executable shmem segments so this function can find
639// an appropriate location.
640BASE_EXPORT bool GetShmemTempDir(bool executable, FilePath* path);
641#endif
642
643// Internal --------------------------------------------------------------------
644
645namespace internal {
646
647// Same as Move but allows paths with traversal components.
648// Use only with extreme care.
649BASE_EXPORT bool MoveUnsafe(const FilePath& from_path,
650 const FilePath& to_path);
651
[email protected]e3177dd52014-08-13 20:22:14652#if defined(OS_WIN)
653// Copy from_path to to_path recursively and then delete from_path recursively.
654// Returns true if all operations succeed.
655// This function simulates Move(), but unlike Move() it works across volumes.
656// This function is not transactional.
657BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path,
658 const FilePath& to_path);
659#endif // defined(OS_WIN)
660
Brian Geffon591e8f22021-04-08 18:33:23661#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID)
662// CopyFileContentsWithSendfile will use the sendfile(2) syscall to perform a
663// file copy without moving the data between kernel and userspace. This is much
664// more efficient than sequences of read(2)/write(2) calls. The |retry_slow|
665// parameter instructs the caller that it should try to fall back to a normal
666// sequences of read(2)/write(2) syscalls.
667//
668// The input file |infile| must be opened for reading and the output file
669// |outfile| must be opened for writing.
670BASE_EXPORT bool CopyFileContentsWithSendfile(File& infile,
671 File& outfile,
672 bool& retry_slow);
673#endif // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID)
674
Victor Costanb5a0a97002019-09-08 04:55:15675// Used by PreReadFile() when no kernel support for prefetching is available.
676bool PreReadFileSlow(const FilePath& file_path, int64_t max_bytes);
677
[email protected]e3177dd52014-08-13 20:22:14678} // namespace internal
679} // namespace base
680
681#endif // BASE_FILES_FILE_UTIL_H_