file_util.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. // 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. // This file contains utility functions for dealing with the local
  5. // filesystem.
  6. #ifndef BASE_FILES_FILE_UTIL_H_
  7. #define BASE_FILES_FILE_UTIL_H_
  8. #include <stddef.h>
  9. #include <stdint.h>
  10. #include <stdio.h>
  11. #include <limits>
  12. #include <set>
  13. #include <string>
  14. #include <vector>
  15. #if defined(OS_POSIX) || defined(OS_FUCHSIA)
  16. #include <sys/stat.h>
  17. #include <unistd.h>
  18. #endif
  19. #include "base/base_export.h"
  20. #include "base/containers/span.h"
  21. #include "base/files/file.h"
  22. #include "base/files/file_path.h"
  23. #include "base/files/scoped_file.h"
  24. #include "base/strings/string16.h"
  25. #include "build/build_config.h"
  26. #if defined(OS_WIN)
  27. #include "base/win/windows_types.h"
  28. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  29. #include "base/file_descriptor_posix.h"
  30. #include "base/logging.h"
  31. #include "base/posix/eintr_wrapper.h"
  32. #endif
  33. namespace base {
  34. class Environment;
  35. class Time;
  36. //-----------------------------------------------------------------------------
  37. // Functions that involve filesystem access or modification:
  38. // Returns an absolute version of a relative path. Returns an empty path on
  39. // error. On POSIX, this function fails if the path does not exist. This
  40. // function can result in I/O so it can be slow.
  41. BASE_EXPORT FilePath MakeAbsoluteFilePath(const FilePath& input);
  42. // Returns the total number of bytes used by all the files under |root_path|.
  43. // If the path does not exist the function returns 0.
  44. //
  45. // This function is implemented using the FileEnumerator class so it is not
  46. // particularly speedy in any platform.
  47. BASE_EXPORT int64_t ComputeDirectorySize(const FilePath& root_path);
  48. // Deletes the given path, whether it's a file or a directory.
  49. // If it's a directory, it's perfectly happy to delete all of the
  50. // directory's contents. Passing true to recursive deletes
  51. // subdirectories and their contents as well.
  52. // Returns true if successful, false otherwise. It is considered successful
  53. // to attempt to delete a file that does not exist.
  54. //
  55. // In POSIX environment and if |path| is a symbolic link, this deletes only
  56. // the symlink. (even if the symlink points to a non-existent file)
  57. //
  58. // WARNING: USING THIS WITH recursive==true IS EQUIVALENT
  59. // TO "rm -rf", SO USE WITH CAUTION.
  60. //
  61. // Note: The |recursive| parameter is in the process of being removed. Use
  62. // DeleteFileRecursively() instead. See https://crbug.com/1009837
  63. BASE_EXPORT bool DeleteFile(const FilePath& path, bool recursive);
  64. // Deletes the given path, whether it's a file or a directory.
  65. // If it's a directory, it's perfectly happy to delete all of the
  66. // directory's contents, including subdirectories and their contents.
  67. // Returns true if successful, false otherwise. It is considered successful
  68. // to attempt to delete a file that does not exist.
  69. //
  70. // In POSIX environment and if |path| is a symbolic link, this deletes only
  71. // the symlink. (even if the symlink points to a non-existent file)
  72. //
  73. // WARNING: USING THIS EQUIVALENT TO "rm -rf", SO USE WITH CAUTION.
  74. BASE_EXPORT bool DeleteFileRecursively(const FilePath& path);
  75. #if defined(OS_WIN)
  76. // Schedules to delete the given path, whether it's a file or a directory, until
  77. // the operating system is restarted.
  78. // Note:
  79. // 1) The file/directory to be deleted should exist in a temp folder.
  80. // 2) The directory to be deleted must be empty.
  81. BASE_EXPORT bool DeleteFileAfterReboot(const FilePath& path);
  82. #endif
  83. // Moves the given path, whether it's a file or a directory.
  84. // If a simple rename is not possible, such as in the case where the paths are
  85. // on different volumes, this will attempt to copy and delete. Returns
  86. // true for success.
  87. // This function fails if either path contains traversal components ('..').
  88. BASE_EXPORT bool Move(const FilePath& from_path, const FilePath& to_path);
  89. // Renames file |from_path| to |to_path|. Both paths must be on the same
  90. // volume, or the function will fail. Destination file will be created
  91. // if it doesn't exist. Prefer this function over Move when dealing with
  92. // temporary files. On Windows it preserves attributes of the target file.
  93. // Returns true on success, leaving *error unchanged.
  94. // Returns false on failure and sets *error appropriately, if it is non-NULL.
  95. BASE_EXPORT bool ReplaceFile(const FilePath& from_path,
  96. const FilePath& to_path,
  97. File::Error* error);
  98. // Copies a single file. Use CopyDirectory() to copy directories.
  99. // This function fails if either path contains traversal components ('..').
  100. // This function also fails if |to_path| is a directory.
  101. //
  102. // On POSIX, if |to_path| is a symlink, CopyFile() will follow the symlink. This
  103. // may have security implications. Use with care.
  104. //
  105. // If |to_path| already exists and is a regular file, it will be overwritten,
  106. // though its permissions will stay the same.
  107. //
  108. // If |to_path| does not exist, it will be created. The new file's permissions
  109. // varies per platform:
  110. //
  111. // - This function keeps the metadata on Windows. The read only bit is not kept.
  112. // - On Mac and iOS, |to_path| retains |from_path|'s permissions, except user
  113. // read/write permissions are always set.
  114. // - On Linux and Android, |to_path| has user read/write permissions only. i.e.
  115. // Always 0600.
  116. // - On ChromeOS, |to_path| has user read/write permissions and group/others
  117. // read permissions. i.e. Always 0644.
  118. BASE_EXPORT bool CopyFile(const FilePath& from_path, const FilePath& to_path);
  119. // Copies the given path, and optionally all subdirectories and their contents
  120. // as well.
  121. //
  122. // If there are files existing under to_path, always overwrite. Returns true
  123. // if successful, false otherwise. Wildcards on the names are not supported.
  124. //
  125. // This function has the same metadata behavior as CopyFile().
  126. //
  127. // If you only need to copy a file use CopyFile, it's faster.
  128. BASE_EXPORT bool CopyDirectory(const FilePath& from_path,
  129. const FilePath& to_path,
  130. bool recursive);
  131. // Like CopyDirectory() except trying to overwrite an existing file will not
  132. // work and will return false.
  133. BASE_EXPORT bool CopyDirectoryExcl(const FilePath& from_path,
  134. const FilePath& to_path,
  135. bool recursive);
  136. // Returns true if the given path exists on the local filesystem,
  137. // false otherwise.
  138. BASE_EXPORT bool PathExists(const FilePath& path);
  139. // Returns true if the given path is writable by the user, false otherwise.
  140. BASE_EXPORT bool PathIsWritable(const FilePath& path);
  141. // Returns true if the given path exists and is a directory, false otherwise.
  142. BASE_EXPORT bool DirectoryExists(const FilePath& path);
  143. // Returns true if the contents of the two files given are equal, false
  144. // otherwise. If either file can't be read, returns false.
  145. BASE_EXPORT bool ContentsEqual(const FilePath& filename1,
  146. const FilePath& filename2);
  147. // Returns true if the contents of the two text files given are equal, false
  148. // otherwise. This routine treats "\r\n" and "\n" as equivalent.
  149. BASE_EXPORT bool TextContentsEqual(const FilePath& filename1,
  150. const FilePath& filename2);
  151. // Reads the file at |path| into |contents| and returns true on success and
  152. // false on error. For security reasons, a |path| containing path traversal
  153. // components ('..') is treated as a read error and |contents| is set to empty.
  154. // In case of I/O error, |contents| holds the data that could be read from the
  155. // file before the error occurred.
  156. // |contents| may be NULL, in which case this function is useful for its side
  157. // effect of priming the disk cache (could be used for unit tests).
  158. BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents);
  159. // Reads the file at |path| into |contents| and returns true on success and
  160. // false on error. For security reasons, a |path| containing path traversal
  161. // components ('..') is treated as a read error and |contents| is set to empty.
  162. // In case of I/O error, |contents| holds the data that could be read from the
  163. // file before the error occurred. When the file size exceeds |max_size|, the
  164. // function returns false with |contents| holding the file truncated to
  165. // |max_size|.
  166. // |contents| may be NULL, in which case this function is useful for its side
  167. // effect of priming the disk cache (could be used for unit tests).
  168. BASE_EXPORT bool ReadFileToStringWithMaxSize(const FilePath& path,
  169. std::string* contents,
  170. size_t max_size);
  171. // As ReadFileToString, but reading from an open stream after seeking to its
  172. // start (if supported by the stream).
  173. BASE_EXPORT bool ReadStreamToString(FILE* stream, std::string* contents);
  174. // As ReadFileToStringWithMaxSize, but reading from an open stream after seeking
  175. // to its start (if supported by the stream).
  176. BASE_EXPORT bool ReadStreamToStringWithMaxSize(FILE* stream,
  177. size_t max_size,
  178. std::string* contents);
  179. #if defined(OS_POSIX) || defined(OS_FUCHSIA)
  180. // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
  181. // in |buffer|. This function is protected against EINTR and partial reads.
  182. // Returns true iff |bytes| bytes have been successfully read from |fd|.
  183. BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes);
  184. // Performs the same function as CreateAndOpenTemporaryStreamInDir(), but
  185. // returns the file-descriptor wrapped in a ScopedFD, rather than the stream
  186. // wrapped in a ScopedFILE.
  187. BASE_EXPORT ScopedFD CreateAndOpenFdForTemporaryFileInDir(const FilePath& dir,
  188. FilePath* path);
  189. #endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
  190. #if defined(OS_POSIX)
  191. // Creates a symbolic link at |symlink| pointing to |target|. Returns
  192. // false on failure.
  193. BASE_EXPORT bool CreateSymbolicLink(const FilePath& target,
  194. const FilePath& symlink);
  195. // Reads the given |symlink| and returns where it points to in |target|.
  196. // Returns false upon failure.
  197. BASE_EXPORT bool ReadSymbolicLink(const FilePath& symlink, FilePath* target);
  198. // Bits and masks of the file permission.
  199. enum FilePermissionBits {
  200. FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO,
  201. FILE_PERMISSION_USER_MASK = S_IRWXU,
  202. FILE_PERMISSION_GROUP_MASK = S_IRWXG,
  203. FILE_PERMISSION_OTHERS_MASK = S_IRWXO,
  204. FILE_PERMISSION_READ_BY_USER = S_IRUSR,
  205. FILE_PERMISSION_WRITE_BY_USER = S_IWUSR,
  206. FILE_PERMISSION_EXECUTE_BY_USER = S_IXUSR,
  207. FILE_PERMISSION_READ_BY_GROUP = S_IRGRP,
  208. FILE_PERMISSION_WRITE_BY_GROUP = S_IWGRP,
  209. FILE_PERMISSION_EXECUTE_BY_GROUP = S_IXGRP,
  210. FILE_PERMISSION_READ_BY_OTHERS = S_IROTH,
  211. FILE_PERMISSION_WRITE_BY_OTHERS = S_IWOTH,
  212. FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH,
  213. };
  214. // Reads the permission of the given |path|, storing the file permission
  215. // bits in |mode|. If |path| is symbolic link, |mode| is the permission of
  216. // a file which the symlink points to.
  217. BASE_EXPORT bool GetPosixFilePermissions(const FilePath& path, int* mode);
  218. // Sets the permission of the given |path|. If |path| is symbolic link, sets
  219. // the permission of a file which the symlink points to.
  220. BASE_EXPORT bool SetPosixFilePermissions(const FilePath& path, int mode);
  221. // Returns true iff |executable| can be found in any directory specified by the
  222. // environment variable in |env|.
  223. BASE_EXPORT bool ExecutableExistsInPath(Environment* env,
  224. const FilePath::StringType& executable);
  225. #if defined(OS_LINUX) || defined(OS_AIX)
  226. // Determine if files under a given |path| can be mapped and then mprotect'd
  227. // PROT_EXEC. This depends on the mount options used for |path|, which vary
  228. // among different Linux distributions and possibly local configuration. It also
  229. // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
  230. // but its kernel allows mprotect with PROT_EXEC anyway.
  231. BASE_EXPORT bool IsPathExecutable(const FilePath& path);
  232. #endif // OS_LINUX || OS_AIX
  233. #endif // OS_POSIX
  234. // Returns true if the given directory is empty
  235. BASE_EXPORT bool IsDirectoryEmpty(const FilePath& dir_path);
  236. // Get the temporary directory provided by the system.
  237. //
  238. // WARNING: In general, you should use CreateTemporaryFile variants below
  239. // instead of this function. Those variants will ensure that the proper
  240. // permissions are set so that other users on the system can't edit them while
  241. // they're open (which can lead to security issues).
  242. BASE_EXPORT bool GetTempDir(FilePath* path);
  243. // Get the home directory. This is more complicated than just getenv("HOME")
  244. // as it knows to fall back on getpwent() etc.
  245. //
  246. // You should not generally call this directly. Instead use DIR_HOME with the
  247. // path service which will use this function but cache the value.
  248. // Path service may also override DIR_HOME.
  249. BASE_EXPORT FilePath GetHomeDir();
  250. // Returns a new temporary file in |dir| with a unique name. The file is opened
  251. // for exclusive read, write, and delete access (note: exclusivity is unique to
  252. // Windows). On Windows, the returned file supports File::DeleteOnClose.
  253. // On success, |temp_file| is populated with the full path to the created file.
  254. BASE_EXPORT File CreateAndOpenTemporaryFileInDir(const FilePath& dir,
  255. FilePath* temp_file);
  256. // Creates a temporary file. The full path is placed in |path|, and the
  257. // function returns true if was successful in creating the file. The file will
  258. // be empty and all handles closed after this function returns.
  259. BASE_EXPORT bool CreateTemporaryFile(FilePath* path);
  260. // Same as CreateTemporaryFile but the file is created in |dir|.
  261. BASE_EXPORT bool CreateTemporaryFileInDir(const FilePath& dir,
  262. FilePath* temp_file);
  263. // Create and open a temporary file stream for exclusive read, write, and delete
  264. // access (note: exclusivity is unique to Windows). The full path is placed in
  265. // |path|. Returns the opened file stream, or null in case of error.
  266. BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStream(FilePath* path);
  267. // Similar to CreateAndOpenTemporaryStream, but the file is created in |dir|.
  268. BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStreamInDir(const FilePath& dir,
  269. FilePath* path);
  270. // Create a new directory. If prefix is provided, the new directory name is in
  271. // the format of prefixyyyy.
  272. // NOTE: prefix is ignored in the POSIX implementation.
  273. // If success, return true and output the full path of the directory created.
  274. BASE_EXPORT bool CreateNewTempDirectory(const FilePath::StringType& prefix,
  275. FilePath* new_temp_path);
  276. // Create a directory within another directory.
  277. // Extra characters will be appended to |prefix| to ensure that the
  278. // new directory does not have the same name as an existing directory.
  279. BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir,
  280. const FilePath::StringType& prefix,
  281. FilePath* new_dir);
  282. // Creates a directory, as well as creating any parent directories, if they
  283. // don't exist. Returns 'true' on successful creation, or if the directory
  284. // already exists. The directory is only readable by the current user.
  285. // Returns true on success, leaving *error unchanged.
  286. // Returns false on failure and sets *error appropriately, if it is non-NULL.
  287. BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path,
  288. File::Error* error);
  289. // Backward-compatible convenience method for the above.
  290. BASE_EXPORT bool CreateDirectory(const FilePath& full_path);
  291. // Returns the file size. Returns true on success.
  292. BASE_EXPORT bool GetFileSize(const FilePath& file_path, int64_t* file_size);
  293. // Sets |real_path| to |path| with symbolic links and junctions expanded.
  294. // On windows, make sure the path starts with a lettered drive.
  295. // |path| must reference a file. Function will fail if |path| points to
  296. // a directory or to a nonexistent path. On windows, this function will
  297. // fail if |real_path| would be longer than MAX_PATH characters.
  298. BASE_EXPORT bool NormalizeFilePath(const FilePath& path, FilePath* real_path);
  299. #if defined(OS_WIN)
  300. // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
  301. // return in |drive_letter_path| the equivalent path that starts with
  302. // a drive letter ("C:\..."). Return false if no such path exists.
  303. BASE_EXPORT bool DevicePathToDriveLetterPath(const FilePath& device_path,
  304. FilePath* drive_letter_path);
  305. // Method that wraps the win32 GetLongPathName API, normalizing the specified
  306. // path to its long form. An example where this is needed is when comparing
  307. // temp file paths. If a username isn't a valid 8.3 short file name (even just a
  308. // lengthy name like "user with long name"), Windows will set the TMP and TEMP
  309. // environment variables to be 8.3 paths. ::GetTempPath (called in
  310. // base::GetTempDir) just uses the value specified by TMP or TEMP, and so can
  311. // return a short path. Returns an empty path on error.
  312. BASE_EXPORT FilePath MakeLongFilePath(const FilePath& input);
  313. // Creates a hard link named |to_file| to the file |from_file|. Both paths
  314. // must be on the same volume, and |from_file| may not name a directory.
  315. // Returns true if the hard link is created, false if it fails.
  316. BASE_EXPORT bool CreateWinHardLink(const FilePath& to_file,
  317. const FilePath& from_file);
  318. #endif
  319. // This function will return if the given file is a symlink or not.
  320. BASE_EXPORT bool IsLink(const FilePath& file_path);
  321. // Returns information about the given file path.
  322. BASE_EXPORT bool GetFileInfo(const FilePath& file_path, File::Info* info);
  323. // Sets the time of the last access and the time of the last modification.
  324. BASE_EXPORT bool TouchFile(const FilePath& path,
  325. const Time& last_accessed,
  326. const Time& last_modified);
  327. // Wrapper for fopen-like calls. Returns non-NULL FILE* on success. The
  328. // underlying file descriptor (POSIX) or handle (Windows) is unconditionally
  329. // configured to not be propagated to child processes.
  330. BASE_EXPORT FILE* OpenFile(const FilePath& filename, const char* mode);
  331. // Closes file opened by OpenFile. Returns true on success.
  332. BASE_EXPORT bool CloseFile(FILE* file);
  333. // Associates a standard FILE stream with an existing File. Note that this
  334. // functions take ownership of the existing File.
  335. BASE_EXPORT FILE* FileToFILE(File file, const char* mode);
  336. // Returns a new handle to the file underlying |file_stream|.
  337. BASE_EXPORT File FILEToFile(FILE* file_stream);
  338. // Truncates an open file to end at the location of the current file pointer.
  339. // This is a cross-platform analog to Windows' SetEndOfFile() function.
  340. BASE_EXPORT bool TruncateFile(FILE* file);
  341. // Reads at most the given number of bytes from the file into the buffer.
  342. // Returns the number of read bytes, or -1 on error.
  343. BASE_EXPORT int ReadFile(const FilePath& filename, char* data, int max_size);
  344. // Writes the given buffer into the file, overwriting any data that was
  345. // previously there. Returns the number of bytes written, or -1 on error.
  346. // If file doesn't exist, it gets created with read/write permissions for all.
  347. // Note that the other variants of WriteFile() below may be easier to use.
  348. BASE_EXPORT int WriteFile(const FilePath& filename, const char* data,
  349. int size);
  350. // Writes |data| into the file, overwriting any data that was previously there.
  351. // Returns true if and only if all of |data| was written. If the file does not
  352. // exist, it gets created with read/write permissions for all.
  353. BASE_EXPORT bool WriteFile(const FilePath& filename, span<const uint8_t> data);
  354. // Another WriteFile() variant that takes a StringPiece so callers don't have to
  355. // do manual conversions from a char span to a uint8_t span.
  356. BASE_EXPORT bool WriteFile(const FilePath& filename, StringPiece data);
  357. #if defined(OS_POSIX) || defined(OS_FUCHSIA)
  358. // Appends |data| to |fd|. Does not close |fd| when done. Returns true iff
  359. // |size| bytes of |data| were written to |fd|.
  360. BASE_EXPORT bool WriteFileDescriptor(const int fd, const char* data, int size);
  361. // Allocates disk space for the file referred to by |fd| for the byte range
  362. // starting at |offset| and continuing for |size| bytes. The file size will be
  363. // changed if |offset|+|len| is greater than the file size. Zeros will fill the
  364. // new space.
  365. // After a successful call, subsequent writes into the specified range are
  366. // guaranteed not to fail because of lack of disk space.
  367. BASE_EXPORT bool AllocateFileRegion(File* file, int64_t offset, size_t size);
  368. #endif
  369. // Appends |data| to |filename|. Returns true iff |size| bytes of |data| were
  370. // written to |filename|.
  371. BASE_EXPORT bool AppendToFile(const FilePath& filename,
  372. const char* data,
  373. int size);
  374. // Gets the current working directory for the process.
  375. BASE_EXPORT bool GetCurrentDirectory(FilePath* path);
  376. // Sets the current working directory for the process.
  377. BASE_EXPORT bool SetCurrentDirectory(const FilePath& path);
  378. // The largest value attempted by GetUniquePath{Number,}.
  379. enum { kMaxUniqueFiles = 100 };
  380. // Returns the number N that makes |path| unique when formatted as " (N)" in a
  381. // suffix to its basename before any file extension, where N is a number between
  382. // 1 and 100 (inclusive). Returns 0 if |path| does not exist (meaning that it is
  383. // unique as-is), or -1 if no such number can be found.
  384. BASE_EXPORT int GetUniquePathNumber(const FilePath& path);
  385. // Returns |path| if it does not exist. Otherwise, returns |path| with the
  386. // suffix " (N)" appended to its basename before any file extension, where N is
  387. // a number between 1 and 100 (inclusive). Returns an empty path if no such
  388. // number can be found.
  389. BASE_EXPORT FilePath GetUniquePath(const FilePath& path);
  390. // Sets the given |fd| to non-blocking mode.
  391. // Returns true if it was able to set it in the non-blocking mode, otherwise
  392. // false.
  393. BASE_EXPORT bool SetNonBlocking(int fd);
  394. // Hints the OS to prefetch the first |max_bytes| of |file_path| into its cache.
  395. //
  396. // If called at the appropriate time, this can reduce the latency incurred by
  397. // feature code that needs to read the file.
  398. //
  399. // |max_bytes| specifies how many bytes should be pre-fetched. It may exceed the
  400. // file's size. Passing in std::numeric_limits<int64_t>::max() is a convenient
  401. // way to get the entire file pre-fetched.
  402. //
  403. // |is_executable| specifies whether the file is to be prefetched as
  404. // executable code or as data. Windows treats the file backed pages in RAM
  405. // differently, and specifying the wrong value results in two copies in RAM.
  406. //
  407. // Returns false if prefetching definitely failed. A return value of true does
  408. // not guarantee that the entire desired range was prefetched.
  409. //
  410. // Calling this before using ::LoadLibrary() on Windows is more efficient memory
  411. // wise, but we must be sure no other threads try to LoadLibrary() the file
  412. // while we are doing the mapping and prefetching, or the process will get a
  413. // private copy of the DLL via COW.
  414. BASE_EXPORT bool PreReadFile(
  415. const FilePath& file_path,
  416. bool is_executable,
  417. int64_t max_bytes = std::numeric_limits<int64_t>::max());
  418. #if defined(OS_POSIX) || defined(OS_FUCHSIA)
  419. // Creates a pipe. Returns true on success, otherwise false.
  420. // On success, |read_fd| will be set to the fd of the read side, and
  421. // |write_fd| will be set to the one of write side. If |non_blocking|
  422. // is set the pipe will be created with O_NONBLOCK|O_CLOEXEC flags set
  423. // otherwise flag is set to zero (default).
  424. BASE_EXPORT bool CreatePipe(ScopedFD* read_fd,
  425. ScopedFD* write_fd,
  426. bool non_blocking = false);
  427. // Creates a non-blocking, close-on-exec pipe.
  428. // This creates a non-blocking pipe that is not intended to be shared with any
  429. // child process. This will be done atomically if the operating system supports
  430. // it. Returns true if it was able to create the pipe, otherwise false.
  431. BASE_EXPORT bool CreateLocalNonBlockingPipe(int fds[2]);
  432. // Sets the given |fd| to close-on-exec mode.
  433. // Returns true if it was able to set it in the close-on-exec mode, otherwise
  434. // false.
  435. BASE_EXPORT bool SetCloseOnExec(int fd);
  436. // Test that |path| can only be changed by a given user and members of
  437. // a given set of groups.
  438. // Specifically, test that all parts of |path| under (and including) |base|:
  439. // * Exist.
  440. // * Are owned by a specific user.
  441. // * Are not writable by all users.
  442. // * Are owned by a member of a given set of groups, or are not writable by
  443. // their group.
  444. // * Are not symbolic links.
  445. // This is useful for checking that a config file is administrator-controlled.
  446. // |base| must contain |path|.
  447. BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base,
  448. const base::FilePath& path,
  449. uid_t owner_uid,
  450. const std::set<gid_t>& group_gids);
  451. #endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
  452. #if defined(OS_MACOSX) && !defined(OS_IOS)
  453. // Is |path| writable only by a user with administrator privileges?
  454. // This function uses Mac OS conventions. The super user is assumed to have
  455. // uid 0, and the administrator group is assumed to be named "admin".
  456. // Testing that |path|, and every parent directory including the root of
  457. // the filesystem, are owned by the superuser, controlled by the group
  458. // "admin", are not writable by all users, and contain no symbolic links.
  459. // Will return false if |path| does not exist.
  460. BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path);
  461. #endif // defined(OS_MACOSX) && !defined(OS_IOS)
  462. // Returns the maximum length of path component on the volume containing
  463. // the directory |path|, in the number of FilePath::CharType, or -1 on failure.
  464. BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path);
  465. #if defined(OS_LINUX) || defined(OS_AIX)
  466. // Broad categories of file systems as returned by statfs() on Linux.
  467. enum FileSystemType {
  468. FILE_SYSTEM_UNKNOWN, // statfs failed.
  469. FILE_SYSTEM_0, // statfs.f_type == 0 means unknown, may indicate AFS.
  470. FILE_SYSTEM_ORDINARY, // on-disk filesystem like ext2
  471. FILE_SYSTEM_NFS,
  472. FILE_SYSTEM_SMB,
  473. FILE_SYSTEM_CODA,
  474. FILE_SYSTEM_MEMORY, // in-memory file system
  475. FILE_SYSTEM_CGROUP, // cgroup control.
  476. FILE_SYSTEM_OTHER, // any other value.
  477. FILE_SYSTEM_TYPE_COUNT
  478. };
  479. // Attempts determine the FileSystemType for |path|.
  480. // Returns false if |path| doesn't exist.
  481. BASE_EXPORT bool GetFileSystemType(const FilePath& path, FileSystemType* type);
  482. #endif
  483. #if defined(OS_POSIX) || defined(OS_FUCHSIA)
  484. // Get a temporary directory for shared memory files. The directory may depend
  485. // on whether the destination is intended for executable files, which in turn
  486. // depends on how /dev/shmem was mounted. As a result, you must supply whether
  487. // you intend to create executable shmem segments so this function can find
  488. // an appropriate location.
  489. BASE_EXPORT bool GetShmemTempDir(bool executable, FilePath* path);
  490. #endif
  491. // Internal --------------------------------------------------------------------
  492. namespace internal {
  493. // Same as Move but allows paths with traversal components.
  494. // Use only with extreme care.
  495. BASE_EXPORT bool MoveUnsafe(const FilePath& from_path,
  496. const FilePath& to_path);
  497. #if defined(OS_WIN)
  498. // Copy from_path to to_path recursively and then delete from_path recursively.
  499. // Returns true if all operations succeed.
  500. // This function simulates Move(), but unlike Move() it works across volumes.
  501. // This function is not transactional.
  502. BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path,
  503. const FilePath& to_path);
  504. #endif // defined(OS_WIN)
  505. // Used by PreReadFile() when no kernel support for prefetching is available.
  506. bool PreReadFileSlow(const FilePath& file_path, int64_t max_bytes);
  507. } // namespace internal
  508. } // namespace base
  509. #endif // BASE_FILES_FILE_UTIL_H_