blob: 06b78339767561b3a5ea6c0905b408a291bed2ac [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
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3920#if defined(OS_POSIX) || defined(OS_FUCHSIA)
21#include <sys/stat.h>
22#include <unistd.h>
23#endif
24
avi543540e2015-12-24 05:15:3225#include "base/base_export.h"
Lei Zhange3aa0b9a2020-06-11 08:59:2326#include "base/callback_forward.h"
Lei Zhangeebbef62020-05-05 20:16:0527#include "base/containers/span.h"
avi543540e2015-12-24 05:15:3228#include "base/files/file.h"
29#include "base/files/file_path.h"
Greg Thompsonf75f5fb2020-04-30 08:13:2530#include "base/files/scoped_file.h"
avi543540e2015-12-24 05:15:3231#include "base/strings/string16.h"
[email protected]e3177dd52014-08-13 20:22:1432#include "build/build_config.h"
33
34#if defined(OS_WIN)
Bruce Dawsonbfdc3fd2018-01-03 20:32:3635#include "base/win/windows_types.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3936#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:1437#include "base/file_descriptor_posix.h"
38#include "base/logging.h"
39#include "base/posix/eintr_wrapper.h"
40#endif
41
42namespace base {
43
thomasanderson1929bb22016-06-24 02:01:0044class Environment;
[email protected]e3177dd52014-08-13 20:22:1445class Time;
46
47//-----------------------------------------------------------------------------
48// Functions that involve filesystem access or modification:
49
50// Returns an absolute version of a relative path. Returns an empty path on
51// error. On POSIX, this function fails if the path does not exist. This
52// function can result in I/O so it can be slow.
53BASE_EXPORT FilePath MakeAbsoluteFilePath(const FilePath& input);
54
55// Returns the total number of bytes used by all the files under |root_path|.
56// If the path does not exist the function returns 0.
57//
58// This function is implemented using the FileEnumerator class so it is not
59// particularly speedy in any platform.
avi543540e2015-12-24 05:15:3260BASE_EXPORT int64_t ComputeDirectorySize(const FilePath& root_path);
[email protected]e3177dd52014-08-13 20:22:1461
62// Deletes the given path, whether it's a file or a directory.
63// If it's a directory, it's perfectly happy to delete all of the
64// directory's contents. Passing true to recursive deletes
65// subdirectories and their contents as well.
66// Returns true if successful, false otherwise. It is considered successful
67// to attempt to delete a file that does not exist.
68//
Lei Zhangaeb72b52019-10-14 22:39:4069// In POSIX environment and if |path| is a symbolic link, this deletes only
[email protected]e3177dd52014-08-13 20:22:1470// the symlink. (even if the symlink points to a non-existent file)
71//
72// WARNING: USING THIS WITH recursive==true IS EQUIVALENT
73// TO "rm -rf", SO USE WITH CAUTION.
Lei Zhangaeb72b52019-10-14 22:39:4074//
75// Note: The |recursive| parameter is in the process of being removed. Use
76// DeleteFileRecursively() instead. See https://crbug.com/1009837
[email protected]e3177dd52014-08-13 20:22:1477BASE_EXPORT bool DeleteFile(const FilePath& path, bool recursive);
78
Lei Zhangaeb72b52019-10-14 22:39:4079// Deletes the given path, whether it's a file or a directory.
80// If it's a directory, it's perfectly happy to delete all of the
81// directory's contents, including subdirectories and their contents.
82// Returns true if successful, false otherwise. It is considered successful
83// to attempt to delete a file that does not exist.
84//
85// In POSIX environment and if |path| is a symbolic link, this deletes only
86// the symlink. (even if the symlink points to a non-existent file)
87//
88// WARNING: USING THIS EQUIVALENT TO "rm -rf", SO USE WITH CAUTION.
89BASE_EXPORT bool DeleteFileRecursively(const FilePath& path);
90
Lei Zhange3aa0b9a2020-06-11 08:59:2391// Simplified way to get a callback to do DeleteFile(path, false) and ignore the
92// DeleteFile() result.
93BASE_EXPORT OnceCallback<void(const FilePath&)> GetDeleteFileCallback();
94
[email protected]e3177dd52014-08-13 20:22:1495#if defined(OS_WIN)
96// Schedules to delete the given path, whether it's a file or a directory, until
97// the operating system is restarted.
98// Note:
99// 1) The file/directory to be deleted should exist in a temp folder.
100// 2) The directory to be deleted must be empty.
101BASE_EXPORT bool DeleteFileAfterReboot(const FilePath& path);
102#endif
103
104// Moves the given path, whether it's a file or a directory.
105// If a simple rename is not possible, such as in the case where the paths are
106// on different volumes, this will attempt to copy and delete. Returns
107// true for success.
108// This function fails if either path contains traversal components ('..').
109BASE_EXPORT bool Move(const FilePath& from_path, const FilePath& to_path);
110
111// Renames file |from_path| to |to_path|. Both paths must be on the same
112// volume, or the function will fail. Destination file will be created
113// if it doesn't exist. Prefer this function over Move when dealing with
114// temporary files. On Windows it preserves attributes of the target file.
115// Returns true on success, leaving *error unchanged.
116// Returns false on failure and sets *error appropriately, if it is non-NULL.
117BASE_EXPORT bool ReplaceFile(const FilePath& from_path,
118 const FilePath& to_path,
119 File::Error* error);
120
Lei Zhang6a0e47ca2017-10-02 23:02:16121// Copies a single file. Use CopyDirectory() to copy directories.
[email protected]e3177dd52014-08-13 20:22:14122// This function fails if either path contains traversal components ('..').
Lei Zhang6a0e47ca2017-10-02 23:02:16123// This function also fails if |to_path| is a directory.
[email protected]e3177dd52014-08-13 20:22:14124//
Lei Zhang6a0e47ca2017-10-02 23:02:16125// On POSIX, if |to_path| is a symlink, CopyFile() will follow the symlink. This
126// may have security implications. Use with care.
127//
128// If |to_path| already exists and is a regular file, it will be overwritten,
129// though its permissions will stay the same.
130//
131// If |to_path| does not exist, it will be created. The new file's permissions
132// varies per platform:
133//
134// - This function keeps the metadata on Windows. The read only bit is not kept.
135// - On Mac and iOS, |to_path| retains |from_path|'s permissions, except user
136// read/write permissions are always set.
137// - On Linux and Android, |to_path| has user read/write permissions only. i.e.
138// Always 0600.
139// - On ChromeOS, |to_path| has user read/write permissions and group/others
140// read permissions. i.e. Always 0644.
[email protected]e3177dd52014-08-13 20:22:14141BASE_EXPORT bool CopyFile(const FilePath& from_path, const FilePath& to_path);
142
143// Copies the given path, and optionally all subdirectories and their contents
144// as well.
145//
146// If there are files existing under to_path, always overwrite. Returns true
147// if successful, false otherwise. Wildcards on the names are not supported.
148//
Eric Carusobca21fc582017-09-28 00:34:34149// This function has the same metadata behavior as CopyFile().
[email protected]e3177dd52014-08-13 20:22:14150//
151// If you only need to copy a file use CopyFile, it's faster.
152BASE_EXPORT bool CopyDirectory(const FilePath& from_path,
153 const FilePath& to_path,
154 bool recursive);
155
Eric Caruso128f0dd2017-12-16 01:32:49156// Like CopyDirectory() except trying to overwrite an existing file will not
157// work and will return false.
158BASE_EXPORT bool CopyDirectoryExcl(const FilePath& from_path,
159 const FilePath& to_path,
160 bool recursive);
161
[email protected]e3177dd52014-08-13 20:22:14162// Returns true if the given path exists on the local filesystem,
163// false otherwise.
164BASE_EXPORT bool PathExists(const FilePath& path);
165
166// Returns true if the given path is writable by the user, false otherwise.
167BASE_EXPORT bool PathIsWritable(const FilePath& path);
168
169// Returns true if the given path exists and is a directory, false otherwise.
170BASE_EXPORT bool DirectoryExists(const FilePath& path);
171
172// Returns true if the contents of the two files given are equal, false
173// otherwise. If either file can't be read, returns false.
174BASE_EXPORT bool ContentsEqual(const FilePath& filename1,
175 const FilePath& filename2);
176
177// Returns true if the contents of the two text files given are equal, false
178// otherwise. This routine treats "\r\n" and "\n" as equivalent.
179BASE_EXPORT bool TextContentsEqual(const FilePath& filename1,
180 const FilePath& filename2);
181
182// Reads the file at |path| into |contents| and returns true on success and
183// false on error. For security reasons, a |path| containing path traversal
184// components ('..') is treated as a read error and |contents| is set to empty.
185// In case of I/O error, |contents| holds the data that could be read from the
186// file before the error occurred.
187// |contents| may be NULL, in which case this function is useful for its side
188// effect of priming the disk cache (could be used for unit tests).
189BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents);
190
191// Reads the file at |path| into |contents| and returns true on success and
192// false on error. For security reasons, a |path| containing path traversal
193// components ('..') is treated as a read error and |contents| is set to empty.
194// In case of I/O error, |contents| holds the data that could be read from the
195// file before the error occurred. When the file size exceeds |max_size|, the
196// function returns false with |contents| holding the file truncated to
197// |max_size|.
198// |contents| may be NULL, in which case this function is useful for its side
199// effect of priming the disk cache (could be used for unit tests).
hashimoto6da2fef2016-02-24 03:39:58200BASE_EXPORT bool ReadFileToStringWithMaxSize(const FilePath& path,
201 std::string* contents,
202 size_t max_size);
[email protected]e3177dd52014-08-13 20:22:14203
Greg Thompson3f7e20f42020-05-02 19:01:11204// As ReadFileToString, but reading from an open stream after seeking to its
205// start (if supported by the stream).
206BASE_EXPORT bool ReadStreamToString(FILE* stream, std::string* contents);
207
208// As ReadFileToStringWithMaxSize, but reading from an open stream after seeking
209// to its start (if supported by the stream).
210BASE_EXPORT bool ReadStreamToStringWithMaxSize(FILE* stream,
211 size_t max_size,
212 std::string* contents);
213
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39214#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:14215
216// Read exactly |bytes| bytes from file descriptor |fd|, storing the result
217// in |buffer|. This function is protected against EINTR and partial reads.
218// Returns true iff |bytes| bytes have been successfully read from |fd|.
219BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes);
220
Greg Thompsonf75f5fb2020-04-30 08:13:25221// Performs the same function as CreateAndOpenTemporaryStreamInDir(), but
222// returns the file-descriptor wrapped in a ScopedFD, rather than the stream
223// wrapped in a ScopedFILE.
Lei Zhangd22c9732019-08-02 16:31:38224BASE_EXPORT ScopedFD CreateAndOpenFdForTemporaryFileInDir(const FilePath& dir,
225 FilePath* path);
Wez45a7b302018-02-22 22:42:39226
Lei Zhangd22c9732019-08-02 16:31:38227#endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39228
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18229#if defined(OS_POSIX)
Kevin Marshalla9f05ec2017-07-14 02:10:05230
[email protected]e3177dd52014-08-13 20:22:14231// Creates a symbolic link at |symlink| pointing to |target|. Returns
232// false on failure.
233BASE_EXPORT bool CreateSymbolicLink(const FilePath& target,
234 const FilePath& symlink);
235
236// Reads the given |symlink| and returns where it points to in |target|.
237// Returns false upon failure.
238BASE_EXPORT bool ReadSymbolicLink(const FilePath& symlink, FilePath* target);
239
240// Bits and masks of the file permission.
241enum FilePermissionBits {
242 FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO,
243 FILE_PERMISSION_USER_MASK = S_IRWXU,
244 FILE_PERMISSION_GROUP_MASK = S_IRWXG,
245 FILE_PERMISSION_OTHERS_MASK = S_IRWXO,
246
247 FILE_PERMISSION_READ_BY_USER = S_IRUSR,
248 FILE_PERMISSION_WRITE_BY_USER = S_IWUSR,
249 FILE_PERMISSION_EXECUTE_BY_USER = S_IXUSR,
250 FILE_PERMISSION_READ_BY_GROUP = S_IRGRP,
251 FILE_PERMISSION_WRITE_BY_GROUP = S_IWGRP,
252 FILE_PERMISSION_EXECUTE_BY_GROUP = S_IXGRP,
253 FILE_PERMISSION_READ_BY_OTHERS = S_IROTH,
254 FILE_PERMISSION_WRITE_BY_OTHERS = S_IWOTH,
255 FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH,
256};
257
258// Reads the permission of the given |path|, storing the file permission
259// bits in |mode|. If |path| is symbolic link, |mode| is the permission of
260// a file which the symlink points to.
261BASE_EXPORT bool GetPosixFilePermissions(const FilePath& path, int* mode);
262// Sets the permission of the given |path|. If |path| is symbolic link, sets
263// the permission of a file which the symlink points to.
264BASE_EXPORT bool SetPosixFilePermissions(const FilePath& path, int mode);
265
thomasanderson1929bb22016-06-24 02:01:00266// Returns true iff |executable| can be found in any directory specified by the
267// environment variable in |env|.
268BASE_EXPORT bool ExecutableExistsInPath(Environment* env,
269 const FilePath::StringType& executable);
270
Sergey Volk76166f5b2018-06-15 17:38:02271#if defined(OS_LINUX) || defined(OS_AIX)
272// Determine if files under a given |path| can be mapped and then mprotect'd
273// PROT_EXEC. This depends on the mount options used for |path|, which vary
274// among different Linux distributions and possibly local configuration. It also
275// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
276// but its kernel allows mprotect with PROT_EXEC anyway.
277BASE_EXPORT bool IsPathExecutable(const FilePath& path);
278#endif // OS_LINUX || OS_AIX
279
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18280#endif // OS_POSIX
[email protected]e3177dd52014-08-13 20:22:14281
282// Returns true if the given directory is empty
283BASE_EXPORT bool IsDirectoryEmpty(const FilePath& dir_path);
284
285// Get the temporary directory provided by the system.
286//
287// WARNING: In general, you should use CreateTemporaryFile variants below
288// instead of this function. Those variants will ensure that the proper
289// permissions are set so that other users on the system can't edit them while
290// they're open (which can lead to security issues).
291BASE_EXPORT bool GetTempDir(FilePath* path);
292
293// Get the home directory. This is more complicated than just getenv("HOME")
294// as it knows to fall back on getpwent() etc.
295//
296// You should not generally call this directly. Instead use DIR_HOME with the
297// path service which will use this function but cache the value.
298// Path service may also override DIR_HOME.
299BASE_EXPORT FilePath GetHomeDir();
300
Greg Thompson3f7e20f42020-05-02 19:01:11301// Returns a new temporary file in |dir| with a unique name. The file is opened
302// for exclusive read, write, and delete access (note: exclusivity is unique to
303// Windows). On Windows, the returned file supports File::DeleteOnClose.
304// On success, |temp_file| is populated with the full path to the created file.
305BASE_EXPORT File CreateAndOpenTemporaryFileInDir(const FilePath& dir,
306 FilePath* temp_file);
307
[email protected]e3177dd52014-08-13 20:22:14308// Creates a temporary file. The full path is placed in |path|, and the
309// function returns true if was successful in creating the file. The file will
310// be empty and all handles closed after this function returns.
311BASE_EXPORT bool CreateTemporaryFile(FilePath* path);
312
313// Same as CreateTemporaryFile but the file is created in |dir|.
314BASE_EXPORT bool CreateTemporaryFileInDir(const FilePath& dir,
315 FilePath* temp_file);
316
Greg Thompson3f7e20f42020-05-02 19:01:11317// Create and open a temporary file stream for exclusive read, write, and delete
318// access (note: exclusivity is unique to Windows). The full path is placed in
319// |path|. Returns the opened file stream, or null in case of error.
Greg Thompsonf75f5fb2020-04-30 08:13:25320BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStream(FilePath* path);
[email protected]e3177dd52014-08-13 20:22:14321
Greg Thompsonf75f5fb2020-04-30 08:13:25322// Similar to CreateAndOpenTemporaryStream, but the file is created in |dir|.
323BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStreamInDir(const FilePath& dir,
324 FilePath* path);
[email protected]e3177dd52014-08-13 20:22:14325
326// Create a new directory. If prefix is provided, the new directory name is in
327// the format of prefixyyyy.
328// NOTE: prefix is ignored in the POSIX implementation.
329// If success, return true and output the full path of the directory created.
330BASE_EXPORT bool CreateNewTempDirectory(const FilePath::StringType& prefix,
331 FilePath* new_temp_path);
332
333// Create a directory within another directory.
334// Extra characters will be appended to |prefix| to ensure that the
335// new directory does not have the same name as an existing directory.
336BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir,
337 const FilePath::StringType& prefix,
338 FilePath* new_dir);
339
340// Creates a directory, as well as creating any parent directories, if they
341// don't exist. Returns 'true' on successful creation, or if the directory
342// already exists. The directory is only readable by the current user.
343// Returns true on success, leaving *error unchanged.
344// Returns false on failure and sets *error appropriately, if it is non-NULL.
345BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path,
346 File::Error* error);
347
348// Backward-compatible convenience method for the above.
349BASE_EXPORT bool CreateDirectory(const FilePath& full_path);
350
351// Returns the file size. Returns true on success.
avi543540e2015-12-24 05:15:32352BASE_EXPORT bool GetFileSize(const FilePath& file_path, int64_t* file_size);
[email protected]e3177dd52014-08-13 20:22:14353
354// Sets |real_path| to |path| with symbolic links and junctions expanded.
355// On windows, make sure the path starts with a lettered drive.
356// |path| must reference a file. Function will fail if |path| points to
357// a directory or to a nonexistent path. On windows, this function will
Alex Gough84ee78c2019-06-06 22:46:23358// fail if |real_path| would be longer than MAX_PATH characters.
[email protected]e3177dd52014-08-13 20:22:14359BASE_EXPORT bool NormalizeFilePath(const FilePath& path, FilePath* real_path);
360
361#if defined(OS_WIN)
362
363// Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
364// return in |drive_letter_path| the equivalent path that starts with
365// a drive letter ("C:\..."). Return false if no such path exists.
366BASE_EXPORT bool DevicePathToDriveLetterPath(const FilePath& device_path,
367 FilePath* drive_letter_path);
368
Bruce Longc343f7e2019-05-11 02:20:12369// Method that wraps the win32 GetLongPathName API, normalizing the specified
370// path to its long form. An example where this is needed is when comparing
371// temp file paths. If a username isn't a valid 8.3 short file name (even just a
372// lengthy name like "user with long name"), Windows will set the TMP and TEMP
373// environment variables to be 8.3 paths. ::GetTempPath (called in
374// base::GetTempDir) just uses the value specified by TMP or TEMP, and so can
375// return a short path. Returns an empty path on error.
376BASE_EXPORT FilePath MakeLongFilePath(const FilePath& input);
David Bienvenuf863412f2019-12-10 21:55:16377
378// Creates a hard link named |to_file| to the file |from_file|. Both paths
379// must be on the same volume, and |from_file| may not name a directory.
380// Returns true if the hard link is created, false if it fails.
381BASE_EXPORT bool CreateWinHardLink(const FilePath& to_file,
382 const FilePath& from_file);
[email protected]e3177dd52014-08-13 20:22:14383#endif
384
385// This function will return if the given file is a symlink or not.
386BASE_EXPORT bool IsLink(const FilePath& file_path);
387
388// Returns information about the given file path.
389BASE_EXPORT bool GetFileInfo(const FilePath& file_path, File::Info* info);
390
391// Sets the time of the last access and the time of the last modification.
392BASE_EXPORT bool TouchFile(const FilePath& path,
393 const Time& last_accessed,
394 const Time& last_modified);
395
grtd0bc44f2017-02-13 17:52:17396// Wrapper for fopen-like calls. Returns non-NULL FILE* on success. The
397// underlying file descriptor (POSIX) or handle (Windows) is unconditionally
398// configured to not be propagated to child processes.
[email protected]e3177dd52014-08-13 20:22:14399BASE_EXPORT FILE* OpenFile(const FilePath& filename, const char* mode);
400
401// Closes file opened by OpenFile. Returns true on success.
402BASE_EXPORT bool CloseFile(FILE* file);
403
404// Associates a standard FILE stream with an existing File. Note that this
405// functions take ownership of the existing File.
406BASE_EXPORT FILE* FileToFILE(File file, const char* mode);
407
Greg Thompson3f7e20f42020-05-02 19:01:11408// Returns a new handle to the file underlying |file_stream|.
409BASE_EXPORT File FILEToFile(FILE* file_stream);
410
[email protected]e3177dd52014-08-13 20:22:14411// Truncates an open file to end at the location of the current file pointer.
412// This is a cross-platform analog to Windows' SetEndOfFile() function.
413BASE_EXPORT bool TruncateFile(FILE* file);
414
415// Reads at most the given number of bytes from the file into the buffer.
416// Returns the number of read bytes, or -1 on error.
417BASE_EXPORT int ReadFile(const FilePath& filename, char* data, int max_size);
418
419// Writes the given buffer into the file, overwriting any data that was
420// previously there. Returns the number of bytes written, or -1 on error.
Andrew091a47b12019-12-12 00:24:00421// If file doesn't exist, it gets created with read/write permissions for all.
Lei Zhangeebbef62020-05-05 20:16:05422// Note that the other variants of WriteFile() below may be easier to use.
[email protected]e3177dd52014-08-13 20:22:14423BASE_EXPORT int WriteFile(const FilePath& filename, const char* data,
424 int size);
425
Lei Zhangeebbef62020-05-05 20:16:05426// Writes |data| into the file, overwriting any data that was previously there.
427// Returns true if and only if all of |data| was written. If the file does not
428// exist, it gets created with read/write permissions for all.
429BASE_EXPORT bool WriteFile(const FilePath& filename, span<const uint8_t> data);
430
431// Another WriteFile() variant that takes a StringPiece so callers don't have to
432// do manual conversions from a char span to a uint8_t span.
433BASE_EXPORT bool WriteFile(const FilePath& filename, StringPiece data);
434
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39435#if defined(OS_POSIX) || defined(OS_FUCHSIA)
chirantan75ea2fd2014-10-07 23:15:30436// Appends |data| to |fd|. Does not close |fd| when done. Returns true iff
437// |size| bytes of |data| were written to |fd|.
438BASE_EXPORT bool WriteFileDescriptor(const int fd, const char* data, int size);
Alex Ilin925adf02019-04-26 11:03:25439
440// Allocates disk space for the file referred to by |fd| for the byte range
441// starting at |offset| and continuing for |size| bytes. The file size will be
442// changed if |offset|+|len| is greater than the file size. Zeros will fill the
443// new space.
444// After a successful call, subsequent writes into the specified range are
445// guaranteed not to fail because of lack of disk space.
446BASE_EXPORT bool AllocateFileRegion(File* file, int64_t offset, size_t size);
[email protected]e3177dd52014-08-13 20:22:14447#endif
448
chirantan75ea2fd2014-10-07 23:15:30449// Appends |data| to |filename|. Returns true iff |size| bytes of |data| were
450// written to |filename|.
451BASE_EXPORT bool AppendToFile(const FilePath& filename,
452 const char* data,
453 int size);
[email protected]e3177dd52014-08-13 20:22:14454
455// Gets the current working directory for the process.
456BASE_EXPORT bool GetCurrentDirectory(FilePath* path);
457
458// Sets the current working directory for the process.
459BASE_EXPORT bool SetCurrentDirectory(const FilePath& path);
460
Greg Thompsonb4abcb42019-08-23 01:42:56461// The largest value attempted by GetUniquePath{Number,}.
462enum { kMaxUniqueFiles = 100 };
[email protected]e3177dd52014-08-13 20:22:14463
Greg Thompsonb4abcb42019-08-23 01:42:56464// Returns the number N that makes |path| unique when formatted as " (N)" in a
465// suffix to its basename before any file extension, where N is a number between
466// 1 and 100 (inclusive). Returns 0 if |path| does not exist (meaning that it is
467// unique as-is), or -1 if no such number can be found.
468BASE_EXPORT int GetUniquePathNumber(const FilePath& path);
469
470// Returns |path| if it does not exist. Otherwise, returns |path| with the
471// suffix " (N)" appended to its basename before any file extension, where N is
472// a number between 1 and 100 (inclusive). Returns an empty path if no such
473// number can be found.
Bruce Longd096e4892019-02-28 17:50:00474BASE_EXPORT FilePath GetUniquePath(const FilePath& path);
475
tfarina060df7e2015-12-16 05:15:32476// Sets the given |fd| to non-blocking mode.
477// Returns true if it was able to set it in the non-blocking mode, otherwise
478// false.
479BASE_EXPORT bool SetNonBlocking(int fd);
480
Victor Costanb5a0a97002019-09-08 04:55:15481// Hints the OS to prefetch the first |max_bytes| of |file_path| into its cache.
482//
483// If called at the appropriate time, this can reduce the latency incurred by
484// feature code that needs to read the file.
485//
486// |max_bytes| specifies how many bytes should be pre-fetched. It may exceed the
487// file's size. Passing in std::numeric_limits<int64_t>::max() is a convenient
488// way to get the entire file pre-fetched.
489//
490// |is_executable| specifies whether the file is to be prefetched as
491// executable code or as data. Windows treats the file backed pages in RAM
492// differently, and specifying the wrong value results in two copies in RAM.
493//
494// Returns false if prefetching definitely failed. A return value of true does
495// not guarantee that the entire desired range was prefetched.
496//
497// Calling this before using ::LoadLibrary() on Windows is more efficient memory
498// wise, but we must be sure no other threads try to LoadLibrary() the file
499// while we are doing the mapping and prefetching, or the process will get a
500// private copy of the DLL via COW.
501BASE_EXPORT bool PreReadFile(
502 const FilePath& file_path,
503 bool is_executable,
504 int64_t max_bytes = std::numeric_limits<int64_t>::max());
505
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39506#if defined(OS_POSIX) || defined(OS_FUCHSIA)
Nick Diego Yamane61bf28ba2019-03-19 14:56:37507
508// Creates a pipe. Returns true on success, otherwise false.
509// On success, |read_fd| will be set to the fd of the read side, and
510// |write_fd| will be set to the one of write side. If |non_blocking|
511// is set the pipe will be created with O_NONBLOCK|O_CLOEXEC flags set
512// otherwise flag is set to zero (default).
513BASE_EXPORT bool CreatePipe(ScopedFD* read_fd,
514 ScopedFD* write_fd,
515 bool non_blocking = false);
516
lhchavez80c77bfd2016-10-08 00:50:53517// Creates a non-blocking, close-on-exec pipe.
518// This creates a non-blocking pipe that is not intended to be shared with any
519// child process. This will be done atomically if the operating system supports
520// it. Returns true if it was able to create the pipe, otherwise false.
521BASE_EXPORT bool CreateLocalNonBlockingPipe(int fds[2]);
522
523// Sets the given |fd| to close-on-exec mode.
524// Returns true if it was able to set it in the close-on-exec mode, otherwise
525// false.
526BASE_EXPORT bool SetCloseOnExec(int fd);
527
[email protected]e3177dd52014-08-13 20:22:14528// Test that |path| can only be changed by a given user and members of
529// a given set of groups.
530// Specifically, test that all parts of |path| under (and including) |base|:
531// * Exist.
532// * Are owned by a specific user.
533// * Are not writable by all users.
534// * Are owned by a member of a given set of groups, or are not writable by
535// their group.
536// * Are not symbolic links.
537// This is useful for checking that a config file is administrator-controlled.
538// |base| must contain |path|.
539BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base,
540 const base::FilePath& path,
541 uid_t owner_uid,
542 const std::set<gid_t>& group_gids);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39543#endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:14544
545#if defined(OS_MACOSX) && !defined(OS_IOS)
546// Is |path| writable only by a user with administrator privileges?
547// This function uses Mac OS conventions. The super user is assumed to have
548// uid 0, and the administrator group is assumed to be named "admin".
549// Testing that |path|, and every parent directory including the root of
550// the filesystem, are owned by the superuser, controlled by the group
551// "admin", are not writable by all users, and contain no symbolic links.
552// Will return false if |path| does not exist.
553BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path);
554#endif // defined(OS_MACOSX) && !defined(OS_IOS)
555
556// Returns the maximum length of path component on the volume containing
557// the directory |path|, in the number of FilePath::CharType, or -1 on failure.
558BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path);
559
rayb0088ee52017-04-26 22:35:08560#if defined(OS_LINUX) || defined(OS_AIX)
[email protected]e3177dd52014-08-13 20:22:14561// Broad categories of file systems as returned by statfs() on Linux.
562enum FileSystemType {
563 FILE_SYSTEM_UNKNOWN, // statfs failed.
564 FILE_SYSTEM_0, // statfs.f_type == 0 means unknown, may indicate AFS.
565 FILE_SYSTEM_ORDINARY, // on-disk filesystem like ext2
566 FILE_SYSTEM_NFS,
567 FILE_SYSTEM_SMB,
568 FILE_SYSTEM_CODA,
569 FILE_SYSTEM_MEMORY, // in-memory file system
570 FILE_SYSTEM_CGROUP, // cgroup control.
571 FILE_SYSTEM_OTHER, // any other value.
572 FILE_SYSTEM_TYPE_COUNT
573};
574
575// Attempts determine the FileSystemType for |path|.
576// Returns false if |path| doesn't exist.
577BASE_EXPORT bool GetFileSystemType(const FilePath& path, FileSystemType* type);
578#endif
579
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39580#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:14581// Get a temporary directory for shared memory files. The directory may depend
582// on whether the destination is intended for executable files, which in turn
583// depends on how /dev/shmem was mounted. As a result, you must supply whether
584// you intend to create executable shmem segments so this function can find
585// an appropriate location.
586BASE_EXPORT bool GetShmemTempDir(bool executable, FilePath* path);
587#endif
588
589// Internal --------------------------------------------------------------------
590
591namespace internal {
592
593// Same as Move but allows paths with traversal components.
594// Use only with extreme care.
595BASE_EXPORT bool MoveUnsafe(const FilePath& from_path,
596 const FilePath& to_path);
597
[email protected]e3177dd52014-08-13 20:22:14598#if defined(OS_WIN)
599// Copy from_path to to_path recursively and then delete from_path recursively.
600// Returns true if all operations succeed.
601// This function simulates Move(), but unlike Move() it works across volumes.
602// This function is not transactional.
603BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path,
604 const FilePath& to_path);
605#endif // defined(OS_WIN)
606
Victor Costanb5a0a97002019-09-08 04:55:15607// Used by PreReadFile() when no kernel support for prefetching is available.
608bool PreReadFileSlow(const FilePath& file_path, int64_t max_bytes);
609
[email protected]e3177dd52014-08-13 20:22:14610} // namespace internal
611} // namespace base
612
613#endif // BASE_FILES_FILE_UTIL_H_