1 // Copyright (c) 2010 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.
5 // This file contains utility functions for dealing with the local
8 #ifndef BASE_FILE_UTIL_H_
9 #define BASE_FILE_UTIL_H_
12 #include "build/build_config.h"
16 #if defined(UNIT_TEST)
19 #elif defined(OS_POSIX)
29 #include "base/basictypes.h"
30 #include "base/file_path.h"
31 #include "base/platform_file.h"
32 #include "base/scoped_ptr.h"
33 #include "base/string16.h"
34 #include "base/time.h"
37 #include "base/eintr_wrapper.h"
38 #include "base/file_descriptor_posix.h"
39 #include "base/logging.h"
48 //-----------------------------------------------------------------------------
49 // Functions that operate purely on a path string w/o touching the filesystem:
51 // Returns true if the given path ends with a path separator character.
52 bool EndsWithSeparator(const FilePath
& path
);
54 // Makes sure that |path| ends with a separator IFF path is a directory that
55 // exists. Returns true if |path| is an existing directory, false otherwise.
56 bool EnsureEndsWithSeparator(FilePath
* path
);
58 // Convert provided relative path into an absolute path. Returns false on
59 // error. On POSIX, this function fails if the path does not exist.
60 bool AbsolutePath(FilePath
* path
);
62 // Returns true if |parent| contains |child|. Both paths are converted to
63 // absolute paths before doing the comparison.
64 bool ContainsPath(const FilePath
& parent
, const FilePath
& child
);
66 //-----------------------------------------------------------------------------
67 // Functions that involve filesystem access or modification:
69 // Returns the number of files matching the current path that were
70 // created on or after the given |file_time|. Doesn't count ".." or ".".
72 // Note for POSIX environments: a file created before |file_time|
73 // can be mis-detected as a newer file due to low precision of
74 // timestmap of file creation time. If you need to avoid such
75 // mis-detection perfectly, you should wait one second before
76 // obtaining |file_time|.
77 int CountFilesCreatedAfter(const FilePath
& path
,
78 const base::Time
& file_time
);
80 // Returns the total number of bytes used by all the files under |root_path|.
81 // If the path does not exist the function returns 0.
83 // This function is implemented using the FileEnumerator class so it is not
84 // particularly speedy in any platform.
85 int64
ComputeDirectorySize(const FilePath
& root_path
);
87 // Returns the total number of bytes used by all files matching the provided
88 // |pattern|, on this |directory| (without recursion). If the path does not
89 // exist the function returns 0.
91 // This function is implemented using the FileEnumerator class so it is not
92 // particularly speedy in any platform.
93 int64
ComputeFilesSize(const FilePath
& directory
,
94 const FilePath::StringType
& pattern
);
96 // Deletes the given path, whether it's a file or a directory.
97 // If it's a directory, it's perfectly happy to delete all of the
98 // directory's contents. Passing true to recursive deletes
99 // subdirectories and their contents as well.
100 // Returns true if successful, false otherwise.
102 // WARNING: USING THIS WITH recursive==true IS EQUIVALENT
103 // TO "rm -rf", SO USE WITH CAUTION.
104 bool Delete(const FilePath
& path
, bool recursive
);
107 // Schedules to delete the given path, whether it's a file or a directory, until
108 // the operating system is restarted.
110 // 1) The file/directory to be deleted should exist in a temp folder.
111 // 2) The directory to be deleted must be empty.
112 bool DeleteAfterReboot(const FilePath
& path
);
115 // Moves the given path, whether it's a file or a directory.
116 // If a simple rename is not possible, such as in the case where the paths are
117 // on different volumes, this will attempt to copy and delete. Returns
119 bool Move(const FilePath
& from_path
, const FilePath
& to_path
);
121 // Renames file |from_path| to |to_path|. Both paths must be on the same
122 // volume, or the function will fail. Destination file will be created
123 // if it doesn't exist. Prefer this function over Move when dealing with
124 // temporary files. On Windows it preserves attributes of the target file.
125 // Returns true on success.
126 bool ReplaceFile(const FilePath
& from_path
, const FilePath
& to_path
);
128 // Copies a single file. Use CopyDirectory to copy directories.
129 bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
);
131 // Copies the given path, and optionally all subdirectories and their contents
133 // If there are files existing under to_path, always overwrite.
134 // Returns true if successful, false otherwise.
135 // Don't use wildcards on the names, it may stop working without notice.
137 // If you only need to copy a file use CopyFile, it's faster.
138 bool CopyDirectory(const FilePath
& from_path
, const FilePath
& to_path
,
141 // Returns true if the given path exists on the local filesystem,
143 bool PathExists(const FilePath
& path
);
145 // Returns true if the given path is writable by the user, false otherwise.
146 bool PathIsWritable(const FilePath
& path
);
148 // Returns true if the given path exists and is a directory, false otherwise.
149 bool DirectoryExists(const FilePath
& path
);
152 // Gets the creation time of the given file (expressed in the local timezone),
153 // and returns it via the creation_time parameter. Returns true if successful,
155 bool GetFileCreationLocalTime(const std::wstring
& filename
,
156 LPSYSTEMTIME creation_time
);
158 // Same as above, but takes a previously-opened file handle instead of a name.
159 bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle
,
160 LPSYSTEMTIME creation_time
);
161 #endif // defined(OS_WIN)
163 // Returns true if the contents of the two files given are equal, false
164 // otherwise. If either file can't be read, returns false.
165 bool ContentsEqual(const FilePath
& filename1
,
166 const FilePath
& filename2
);
168 // Returns true if the contents of the two text files given are equal, false
169 // otherwise. This routine treats "\r\n" and "\n" as equivalent.
170 bool TextContentsEqual(const FilePath
& filename1
, const FilePath
& filename2
);
172 // Read the file at |path| into |contents|, returning true on success.
173 // |contents| may be NULL, in which case this function is useful for its
174 // side effect of priming the disk cache.
175 // Useful for unit tests.
176 bool ReadFileToString(const FilePath
& path
, std::string
* contents
);
178 #if defined(OS_POSIX)
179 // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
180 // in |buffer|. This function is protected against EINTR and partial reads.
181 // Returns true iff |bytes| bytes have been successfuly read from |fd|.
182 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
);
183 #endif // defined(OS_POSIX)
186 // Resolve Windows shortcut (.LNK file)
187 // This methods tries to resolve a shortcut .LNK file. If the |path| is valid
188 // returns true and puts the target into the |path|, otherwise returns
189 // false leaving the path as it is.
190 bool ResolveShortcut(FilePath
* path
);
192 // Create a Windows shortcut (.LNK file)
193 // This method creates a shortcut link using the information given. Ensure
194 // you have initialized COM before calling into this function. 'source'
195 // and 'destination' parameters are required, everything else can be NULL.
196 // 'source' is the existing file, 'destination' is the new link file to be
197 // created; for best results pass the filename with the .lnk extension.
198 // The 'icon' can specify a dll or exe in which case the icon index is the
199 // resource id. 'app_id' is the app model id for the shortcut on Win7.
200 // Note that if the shortcut exists it will overwrite it.
201 bool CreateShortcutLink(const wchar_t *source
, const wchar_t *destination
,
202 const wchar_t *working_dir
, const wchar_t *arguments
,
203 const wchar_t *description
, const wchar_t *icon
,
204 int icon_index
, const wchar_t* app_id
);
206 // Update a Windows shortcut (.LNK file). This method assumes the shortcut
207 // link already exists (otherwise false is returned). Ensure you have
208 // initialized COM before calling into this function. Only 'destination'
209 // parameter is required, everything else can be NULL (but if everything else
210 // is NULL no changes are made to the shortcut). 'destination' is the link
211 // file to be updated. 'app_id' is the app model id for the shortcut on Win7.
212 // For best results pass the filename with the .lnk extension.
213 bool UpdateShortcutLink(const wchar_t *source
, const wchar_t *destination
,
214 const wchar_t *working_dir
, const wchar_t *arguments
,
215 const wchar_t *description
, const wchar_t *icon
,
216 int icon_index
, const wchar_t* app_id
);
218 // Pins a shortcut to the Windows 7 taskbar. The shortcut file must already
219 // exist and be a shortcut that points to an executable.
220 bool TaskbarPinShortcutLink(const wchar_t* shortcut
);
222 // Unpins a shortcut from the Windows 7 taskbar. The shortcut must exist and
223 // already be pinned to the taskbar.
224 bool TaskbarUnpinShortcutLink(const wchar_t* shortcut
);
226 // Copy from_path to to_path recursively and then delete from_path recursively.
227 // Returns true if all operations succeed.
228 // This function simulates Move(), but unlike Move() it works across volumes.
229 // This fuction is not transactional.
230 bool CopyAndDeleteDirectory(const FilePath
& from_path
,
231 const FilePath
& to_path
);
232 #endif // defined(OS_WIN)
234 // Return true if the given directory is empty
235 bool IsDirectoryEmpty(const FilePath
& dir_path
);
237 // Get the temporary directory provided by the system.
238 // WARNING: DON'T USE THIS. If you want to create a temporary file, use one of
239 // the functions below.
240 bool GetTempDir(FilePath
* path
);
241 // Get a temporary directory for shared memory files.
242 // Only useful on POSIX; redirects to GetTempDir() on Windows.
243 bool GetShmemTempDir(FilePath
* path
);
245 // Get the home directory. This is more complicated than just getenv("HOME")
246 // as it knows to fall back on getpwent() etc.
247 FilePath
GetHomeDir();
249 // Creates a temporary file. The full path is placed in |path|, and the
250 // function returns true if was successful in creating the file. The file will
251 // be empty and all handles closed after this function returns.
252 bool CreateTemporaryFile(FilePath
* path
);
254 // Same as CreateTemporaryFile but the file is created in |dir|.
255 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
);
257 // Create and open a temporary file. File is opened for read/write.
258 // The full path is placed in |path|.
259 // Returns a handle to the opened file or NULL if an error occured.
260 FILE* CreateAndOpenTemporaryFile(FilePath
* path
);
261 // Like above but for shmem files. Only useful for POSIX.
262 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
);
263 // Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
264 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
);
266 // Create a new directory. If prefix is provided, the new directory name is in
267 // the format of prefixyyyy.
268 // NOTE: prefix is ignored in the POSIX implementation.
269 // If success, return true and output the full path of the directory created.
270 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
271 FilePath
* new_temp_path
);
273 // Create a directory within another directory.
274 // Extra characters will be appended to |prefix| to ensure that the
275 // new directory does not have the same name as an existing directory.
276 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
277 const FilePath::StringType
& prefix
,
280 // Creates a directory, as well as creating any parent directories, if they
281 // don't exist. Returns 'true' on successful creation, or if the directory
282 // already exists. The directory is only readable by the current user.
283 bool CreateDirectory(const FilePath
& full_path
);
286 // Added for debugging an issue where CreateDirectory() fails. LOG(*) does
287 // not work, because the failure happens in a sandboxed process.
288 // TODO(skerner): Remove once crbug/35198 is resolved.
289 bool CreateDirectoryExtraLogging(const FilePath
& full_path
,
290 std::ostream
& error
);
291 #endif // defined (OS_WIN)
293 // Returns the file size. Returns true on success.
294 bool GetFileSize(const FilePath
& file_path
, int64
* file_size
);
296 // Returns true if the given path's base name is ".".
297 bool IsDot(const FilePath
& path
);
299 // Returns true if the given path's base name is "..".
300 bool IsDotDot(const FilePath
& path
);
302 // Sets |real_path| to |path| with symbolic links and junctions expanded.
303 // On windows, make sure the path starts with a lettered drive.
304 // |path| must reference a file. Function will fail if |path| points to
305 // a directory or to a nonexistent path. On windows, this function will
306 // fail if |path| is a junction or symlink that points to an empty file,
307 // or if |real_path| would be longer than MAX_PATH characters.
308 bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
);
311 // Given an existing file in |path|, it returns in |real_path| the path
312 // in the native NT format, of the form "\Device\HarddiskVolumeXX\..".
313 // Returns false it it fails. Empty files cannot be resolved with this
315 bool NormalizeToNativeFilePath(const FilePath
& path
, FilePath
* nt_path
);
318 // Used to hold information about a given file path. See GetFileInfo below.
320 // The size of the file in bytes. Undefined when is_directory is true.
323 // True if the file corresponds to a directory.
326 // The last modified time of a file.
327 base::Time last_modified
;
329 // Add additional fields here as needed.
332 // Returns information about the given file path.
333 bool GetFileInfo(const FilePath
& file_path
, FileInfo
* info
);
335 // Set the time of the last modification. Useful for unit tests.
336 bool SetLastModifiedTime(const FilePath
& file_path
, base::Time last_modified
);
338 #if defined(OS_POSIX)
339 // Store inode number of |path| in |inode|. Return true on success.
340 bool GetInode(const FilePath
& path
, ino_t
* inode
);
343 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
344 FILE* OpenFile(const FilePath
& filename
, const char* mode
);
346 // Closes file opened by OpenFile. Returns true on success.
347 bool CloseFile(FILE* file
);
349 // Truncates an open file to end at the location of the current file pointer.
350 // This is a cross-platform analog to Windows' SetEndOfFile() function.
351 bool TruncateFile(FILE* file
);
353 // Reads the given number of bytes from the file into the buffer. Returns
354 // the number of read bytes, or -1 on error.
355 int ReadFile(const FilePath
& filename
, char* data
, int size
);
357 // Writes the given buffer into the file, overwriting any data that was
358 // previously there. Returns the number of bytes written, or -1 on error.
359 int WriteFile(const FilePath
& filename
, const char* data
, int size
);
360 #if defined(OS_POSIX)
361 // Append the data to |fd|. Does not close |fd| when done.
362 int WriteFileDescriptor(const int fd
, const char* data
, int size
);
365 // Gets the current working directory for the process.
366 bool GetCurrentDirectory(FilePath
* path
);
368 // Sets the current working directory for the process.
369 bool SetCurrentDirectory(const FilePath
& path
);
371 // A class to handle auto-closing of FILE*'s.
372 class ScopedFILEClose
{
374 inline void operator()(FILE* x
) const {
381 typedef scoped_ptr_malloc
<FILE, ScopedFILEClose
> ScopedFILE
;
383 #if defined(OS_POSIX)
384 // A class to handle auto-closing of FDs.
385 class ScopedFDClose
{
387 inline void operator()(int* x
) const {
389 if (HANDLE_EINTR(close(*x
)) < 0)
390 PLOG(ERROR
) << "close";
395 typedef scoped_ptr_malloc
<int, ScopedFDClose
> ScopedFD
;
398 // A class for enumerating the files in a provided path. The order of the
399 // results is not guaranteed.
401 // DO NOT USE FROM THE MAIN THREAD of your application unless it is a test
402 // program where latency does not matter. This class is blocking.
403 class FileEnumerator
{
406 typedef WIN32_FIND_DATA FindInfo
;
407 #elif defined(OS_POSIX)
410 std::string filename
;
416 DIRECTORIES
= 1 << 1,
417 INCLUDE_DOT_DOT
= 1 << 2,
418 #if defined(OS_POSIX)
419 SHOW_SYM_LINKS
= 1 << 4,
423 // |root_path| is the starting directory to search for. It may or may not end
426 // If |recursive| is true, this will enumerate all matches in any
427 // subdirectories matched as well. It does a breadth-first search, so all
428 // files in one directory will be returned before any files in a
431 // |file_type| specifies whether the enumerator should match files,
432 // directories, or both.
434 // |pattern| is an optional pattern for which files to match. This
435 // works like shell globbing. For example, "*.txt" or "Foo???.doc".
436 // However, be careful in specifying patterns that aren't cross platform
437 // since the underlying code uses OS-specific matching routines. In general,
438 // Windows matching is less featureful than others, so test there first.
439 // If unspecified, this will match all files.
440 // NOTE: the pattern only matches the contents of root_path, not files in
441 // recursive subdirectories.
442 // TODO(erikkay): Fix the pattern matching to work at all levels.
443 FileEnumerator(const FilePath
& root_path
,
445 FileEnumerator::FILE_TYPE file_type
);
446 FileEnumerator(const FilePath
& root_path
,
448 FileEnumerator::FILE_TYPE file_type
,
449 const FilePath::StringType
& pattern
);
452 // Returns an empty string if there are no more results.
455 // Write the file info into |info|.
456 void GetFindInfo(FindInfo
* info
);
458 // Looks inside a FindInfo and determines if it's a directory.
459 static bool IsDirectory(const FindInfo
& info
);
461 static FilePath
GetFilename(const FindInfo
& find_info
);
464 // Returns true if the given path should be skipped in enumeration.
465 bool ShouldSkip(const FilePath
& path
);
469 WIN32_FIND_DATA find_data_
;
471 #elif defined(OS_POSIX)
475 } DirectoryEntryInfo
;
477 // Read the filenames in source into the vector of DirectoryEntryInfo's
478 static bool ReadDirectory(std::vector
<DirectoryEntryInfo
>* entries
,
479 const FilePath
& source
, bool show_links
);
481 // The files in the current directory
482 std::vector
<DirectoryEntryInfo
> directory_entries_
;
484 // The next entry to use from the directory_entries_ vector
485 size_t current_directory_entry_
;
490 FILE_TYPE file_type_
;
491 FilePath::StringType pattern_
; // Empty when we want to find everything.
493 // Set to true when there is a find operation open. This way, we can lazily
494 // start the operations when the caller calls Next().
497 // A stack that keeps track of which subdirectories we still need to
498 // enumerate in the breadth-first search.
499 std::stack
<FilePath
> pending_paths_
;
501 DISALLOW_COPY_AND_ASSIGN(FileEnumerator
);
504 class MemoryMappedFile
{
506 // The default constructor sets all members to invalid/null values.
510 // Opens an existing file and maps it into memory. Access is restricted to
511 // read only. If this object already points to a valid memory mapped file
512 // then this method will fail and return false. If it cannot open the file,
513 // the file does not exist, or the memory mapping fails, it will return false.
514 // Later we may want to allow the user to specify access.
515 bool Initialize(const FilePath
& file_name
);
516 // As above, but works with an already-opened file. MemoryMappedFile will take
517 // ownership of |file| and close it when done.
518 bool Initialize(base::PlatformFile file
);
520 const uint8
* data() const { return data_
; }
521 size_t length() const { return length_
; }
523 // Is file_ a valid file handle that points to an open, memory mapped file?
527 // Open the given file and pass it to MapFileToMemoryInternal().
528 bool MapFileToMemory(const FilePath
& file_name
);
530 // Map the file to memory, set data_ to that memory address. Return true on
531 // success, false on any kind of failure. This is a helper for Initialize().
532 bool MapFileToMemoryInternal();
534 // Closes all open handles. Later we may want to make this public.
537 base::PlatformFile file_
;
539 HANDLE file_mapping_
;
544 DISALLOW_COPY_AND_ASSIGN(MemoryMappedFile
);
547 // Renames a file using the SHFileOperation API to ensure that the target file
548 // gets the correct default security descriptor in the new path.
549 bool RenameFileAndResetSecurityDescriptor(
550 const FilePath
& source_file_path
,
551 const FilePath
& target_file_path
);
553 // Returns whether the file has been modified since a particular date.
554 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo
& find_info
,
555 const base::Time
& cutoff_time
);
559 inline bool MakeFileUnreadable(const FilePath
& path
) {
560 #if defined(OS_POSIX)
561 struct stat stat_buf
;
562 if (stat(path
.value().c_str(), &stat_buf
) != 0)
564 stat_buf
.st_mode
&= ~(S_IRUSR
| S_IRGRP
| S_IROTH
);
566 return chmod(path
.value().c_str(), stat_buf
.st_mode
) == 0;
568 #elif defined(OS_WIN)
570 PSECURITY_DESCRIPTOR security_descriptor
;
571 if (GetNamedSecurityInfo(const_cast<wchar_t*>(path
.value().c_str()),
573 DACL_SECURITY_INFORMATION
, NULL
, NULL
, &old_dacl
,
574 NULL
, &security_descriptor
) != ERROR_SUCCESS
)
577 // Deny Read access for the current user.
578 EXPLICIT_ACCESS change
;
579 change
.grfAccessPermissions
= GENERIC_READ
;
580 change
.grfAccessMode
= DENY_ACCESS
;
581 change
.grfInheritance
= 0;
582 change
.Trustee
.pMultipleTrustee
= NULL
;
583 change
.Trustee
.MultipleTrusteeOperation
= NO_MULTIPLE_TRUSTEE
;
584 change
.Trustee
.TrusteeForm
= TRUSTEE_IS_NAME
;
585 change
.Trustee
.TrusteeType
= TRUSTEE_IS_USER
;
586 change
.Trustee
.ptstrName
= L
"CURRENT_USER";
589 if (SetEntriesInAcl(1, &change
, old_dacl
, &new_dacl
) != ERROR_SUCCESS
) {
590 LocalFree(security_descriptor
);
594 DWORD rc
= SetNamedSecurityInfo(const_cast<wchar_t*>(path
.value().c_str()),
595 SE_FILE_OBJECT
, DACL_SECURITY_INFORMATION
,
596 NULL
, NULL
, new_dacl
, NULL
);
597 LocalFree(security_descriptor
);
600 return rc
== ERROR_SUCCESS
;
610 // Loads the file passed in as an image section and touches pages to avoid
611 // subsequent hard page faults during LoadLibrary. The size to be pre read
612 // is passed in. If it is 0 then the whole file is paged in. The step size
613 // which indicates the number of bytes to skip after every page touched is
615 bool PreReadImage(const wchar_t* file_path
, size_t size_to_read
,
619 #if defined(OS_LINUX)
620 // Broad categories of file systems as returned by statfs() on Linux.
621 enum FileSystemType
{
622 FILE_SYSTEM_UNKNOWN
, // statfs failed.
623 FILE_SYSTEM_0
, // statfs.f_type == 0 means unknown, may indicate AFS.
624 FILE_SYSTEM_ORDINARY
, // on-disk filesystem like ext2
628 FILE_SYSTEM_MEMORY
, // in-memory file system
629 FILE_SYSTEM_OTHER
, // any other value.
630 FILE_SYSTEM_TYPE_COUNT
633 // Attempts determine the FileSystemType for |path|.
634 // Returns false if |path| doesn't exist.
635 bool GetFileSystemType(const FilePath
& path
, FileSystemType
* type
);
638 } // namespace file_util
640 // Deprecated functions have been moved to this separate header file,
641 // which must be included last after all the above definitions.
642 #include "base/file_util_deprecated.h"
644 #endif // BASE_FILE_UTIL_H_