Home | History | Annotate | Download | only in base
      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 
      5 #include "base/file_util.h"
      6 
      7 #include <windows.h>
      8 #include <psapi.h>
      9 #include <shellapi.h>
     10 #include <shlobj.h>
     11 #include <time.h>
     12 
     13 #include <algorithm>
     14 #include <limits>
     15 #include <string>
     16 
     17 #include "base/files/file_path.h"
     18 #include "base/logging.h"
     19 #include "base/metrics/histogram.h"
     20 #include "base/process/process_handle.h"
     21 #include "base/rand_util.h"
     22 #include "base/strings/string_number_conversions.h"
     23 #include "base/strings/string_util.h"
     24 #include "base/strings/utf_string_conversions.h"
     25 #include "base/threading/thread_restrictions.h"
     26 #include "base/time/time.h"
     27 #include "base/win/scoped_handle.h"
     28 #include "base/win/windows_version.h"
     29 
     30 namespace base {
     31 
     32 namespace {
     33 
     34 const DWORD kFileShareAll =
     35     FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
     36 
     37 bool ShellCopy(const FilePath& from_path,
     38                const FilePath& to_path,
     39                bool recursive) {
     40   // WinXP SHFileOperation doesn't like trailing separators.
     41   FilePath stripped_from = from_path.StripTrailingSeparators();
     42   FilePath stripped_to = to_path.StripTrailingSeparators();
     43 
     44   ThreadRestrictions::AssertIOAllowed();
     45 
     46   // NOTE: I suspect we could support longer paths, but that would involve
     47   // analyzing all our usage of files.
     48   if (stripped_from.value().length() >= MAX_PATH ||
     49       stripped_to.value().length() >= MAX_PATH) {
     50     return false;
     51   }
     52 
     53   // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
     54   // so we have to use wcscpy because wcscpy_s writes non-NULLs
     55   // into the rest of the buffer.
     56   wchar_t double_terminated_path_from[MAX_PATH + 1] = {0};
     57   wchar_t double_terminated_path_to[MAX_PATH + 1] = {0};
     58 #pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
     59   wcscpy(double_terminated_path_from, stripped_from.value().c_str());
     60 #pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
     61   wcscpy(double_terminated_path_to, stripped_to.value().c_str());
     62 
     63   SHFILEOPSTRUCT file_operation = {0};
     64   file_operation.wFunc = FO_COPY;
     65   file_operation.pFrom = double_terminated_path_from;
     66   file_operation.pTo = double_terminated_path_to;
     67   file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION |
     68                           FOF_NOCONFIRMMKDIR;
     69   if (!recursive)
     70     file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
     71 
     72   return (SHFileOperation(&file_operation) == 0);
     73 }
     74 
     75 }  // namespace
     76 
     77 FilePath MakeAbsoluteFilePath(const FilePath& input) {
     78   ThreadRestrictions::AssertIOAllowed();
     79   wchar_t file_path[MAX_PATH];
     80   if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
     81     return FilePath();
     82   return FilePath(file_path);
     83 }
     84 
     85 bool DeleteFile(const FilePath& path, bool recursive) {
     86   ThreadRestrictions::AssertIOAllowed();
     87 
     88   if (path.value().length() >= MAX_PATH)
     89     return false;
     90 
     91   if (!recursive) {
     92     // If not recursing, then first check to see if |path| is a directory.
     93     // If it is, then remove it with RemoveDirectory.
     94     PlatformFileInfo file_info;
     95     if (GetFileInfo(path, &file_info) && file_info.is_directory)
     96       return RemoveDirectory(path.value().c_str()) != 0;
     97 
     98     // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
     99     // because it should be faster. If DeleteFile fails, then we fall through
    100     // to SHFileOperation, which will do the right thing.
    101     if (::DeleteFile(path.value().c_str()) != 0)
    102       return true;
    103   }
    104 
    105   // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
    106   // so we have to use wcscpy because wcscpy_s writes non-NULLs
    107   // into the rest of the buffer.
    108   wchar_t double_terminated_path[MAX_PATH + 1] = {0};
    109 #pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
    110   wcscpy(double_terminated_path, path.value().c_str());
    111 
    112   SHFILEOPSTRUCT file_operation = {0};
    113   file_operation.wFunc = FO_DELETE;
    114   file_operation.pFrom = double_terminated_path;
    115   file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
    116   if (!recursive)
    117     file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
    118   int err = SHFileOperation(&file_operation);
    119 
    120   // Since we're passing flags to the operation telling it to be silent,
    121   // it's possible for the operation to be aborted/cancelled without err
    122   // being set (although MSDN doesn't give any scenarios for how this can
    123   // happen).  See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
    124   if (file_operation.fAnyOperationsAborted)
    125     return false;
    126 
    127   // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
    128   // an empty directory and some return 0x402 when they should be returning
    129   // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
    130   return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402);
    131 }
    132 
    133 bool DeleteFileAfterReboot(const FilePath& path) {
    134   ThreadRestrictions::AssertIOAllowed();
    135 
    136   if (path.value().length() >= MAX_PATH)
    137     return false;
    138 
    139   return MoveFileEx(path.value().c_str(), NULL,
    140                     MOVEFILE_DELAY_UNTIL_REBOOT |
    141                         MOVEFILE_REPLACE_EXISTING) != FALSE;
    142 }
    143 
    144 bool ReplaceFile(const FilePath& from_path,
    145                  const FilePath& to_path,
    146                  PlatformFileError* error) {
    147   ThreadRestrictions::AssertIOAllowed();
    148   // Try a simple move first.  It will only succeed when |to_path| doesn't
    149   // already exist.
    150   if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
    151     return true;
    152   // Try the full-blown replace if the move fails, as ReplaceFile will only
    153   // succeed when |to_path| does exist. When writing to a network share, we may
    154   // not be able to change the ACLs. Ignore ACL errors then
    155   // (REPLACEFILE_IGNORE_MERGE_ERRORS).
    156   if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
    157                     REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
    158     return true;
    159   }
    160   if (error)
    161     *error = LastErrorToPlatformFileError(GetLastError());
    162   return false;
    163 }
    164 
    165 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
    166                    bool recursive) {
    167   ThreadRestrictions::AssertIOAllowed();
    168 
    169   if (recursive)
    170     return ShellCopy(from_path, to_path, true);
    171 
    172   // The following code assumes that from path is a directory.
    173   DCHECK(DirectoryExists(from_path));
    174 
    175   // Instead of creating a new directory, we copy the old one to include the
    176   // security information of the folder as part of the copy.
    177   if (!PathExists(to_path)) {
    178     // Except that Vista fails to do that, and instead do a recursive copy if
    179     // the target directory doesn't exist.
    180     if (base::win::GetVersion() >= base::win::VERSION_VISTA)
    181       CreateDirectory(to_path);
    182     else
    183       ShellCopy(from_path, to_path, false);
    184   }
    185 
    186   FilePath directory = from_path.Append(L"*.*");
    187   return ShellCopy(directory, to_path, false);
    188 }
    189 
    190 bool PathExists(const FilePath& path) {
    191   ThreadRestrictions::AssertIOAllowed();
    192   return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
    193 }
    194 
    195 bool PathIsWritable(const FilePath& path) {
    196   ThreadRestrictions::AssertIOAllowed();
    197   HANDLE dir =
    198       CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
    199                  NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    200 
    201   if (dir == INVALID_HANDLE_VALUE)
    202     return false;
    203 
    204   CloseHandle(dir);
    205   return true;
    206 }
    207 
    208 bool DirectoryExists(const FilePath& path) {
    209   ThreadRestrictions::AssertIOAllowed();
    210   DWORD fileattr = GetFileAttributes(path.value().c_str());
    211   if (fileattr != INVALID_FILE_ATTRIBUTES)
    212     return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
    213   return false;
    214 }
    215 
    216 bool GetTempDir(FilePath* path) {
    217   wchar_t temp_path[MAX_PATH + 1];
    218   DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
    219   if (path_len >= MAX_PATH || path_len <= 0)
    220     return false;
    221   // TODO(evanm): the old behavior of this function was to always strip the
    222   // trailing slash.  We duplicate this here, but it shouldn't be necessary
    223   // when everyone is using the appropriate FilePath APIs.
    224   *path = FilePath(temp_path).StripTrailingSeparators();
    225   return true;
    226 }
    227 
    228 bool GetShmemTempDir(bool executable, FilePath* path) {
    229   return GetTempDir(path);
    230 }
    231 
    232 bool CreateTemporaryFile(FilePath* path) {
    233   ThreadRestrictions::AssertIOAllowed();
    234 
    235   FilePath temp_file;
    236 
    237   if (!GetTempDir(path))
    238     return false;
    239 
    240   if (CreateTemporaryFileInDir(*path, &temp_file)) {
    241     *path = temp_file;
    242     return true;
    243   }
    244 
    245   return false;
    246 }
    247 
    248 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
    249   ThreadRestrictions::AssertIOAllowed();
    250   return CreateAndOpenTemporaryFile(path);
    251 }
    252 
    253 // On POSIX we have semantics to create and open a temporary file
    254 // atomically.
    255 // TODO(jrg): is there equivalent call to use on Windows instead of
    256 // going 2-step?
    257 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
    258   ThreadRestrictions::AssertIOAllowed();
    259   if (!CreateTemporaryFileInDir(dir, path)) {
    260     return NULL;
    261   }
    262   // Open file in binary mode, to avoid problems with fwrite. On Windows
    263   // it replaces \n's with \r\n's, which may surprise you.
    264   // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
    265   return OpenFile(*path, "wb+");
    266 }
    267 
    268 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
    269   ThreadRestrictions::AssertIOAllowed();
    270 
    271   wchar_t temp_name[MAX_PATH + 1];
    272 
    273   if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
    274     DPLOG(WARNING) << "Failed to get temporary file name in "
    275                    << UTF16ToUTF8(dir.value());
    276     return false;
    277   }
    278 
    279   wchar_t long_temp_name[MAX_PATH + 1];
    280   DWORD long_name_len = GetLongPathName(temp_name, long_temp_name, MAX_PATH);
    281   if (long_name_len > MAX_PATH || long_name_len == 0) {
    282     // GetLongPathName() failed, but we still have a temporary file.
    283     *temp_file = FilePath(temp_name);
    284     return true;
    285   }
    286 
    287   FilePath::StringType long_temp_name_str;
    288   long_temp_name_str.assign(long_temp_name, long_name_len);
    289   *temp_file = FilePath(long_temp_name_str);
    290   return true;
    291 }
    292 
    293 bool CreateTemporaryDirInDir(const FilePath& base_dir,
    294                              const FilePath::StringType& prefix,
    295                              FilePath* new_dir) {
    296   ThreadRestrictions::AssertIOAllowed();
    297 
    298   FilePath path_to_create;
    299 
    300   for (int count = 0; count < 50; ++count) {
    301     // Try create a new temporary directory with random generated name. If
    302     // the one exists, keep trying another path name until we reach some limit.
    303     string16 new_dir_name;
    304     new_dir_name.assign(prefix);
    305     new_dir_name.append(IntToString16(GetCurrentProcId()));
    306     new_dir_name.push_back('_');
    307     new_dir_name.append(IntToString16(RandInt(0, kint16max)));
    308 
    309     path_to_create = base_dir.Append(new_dir_name);
    310     if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
    311       *new_dir = path_to_create;
    312       return true;
    313     }
    314   }
    315 
    316   return false;
    317 }
    318 
    319 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
    320                             FilePath* new_temp_path) {
    321   ThreadRestrictions::AssertIOAllowed();
    322 
    323   FilePath system_temp_dir;
    324   if (!GetTempDir(&system_temp_dir))
    325     return false;
    326 
    327   return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
    328 }
    329 
    330 bool CreateDirectoryAndGetError(const FilePath& full_path,
    331                                 PlatformFileError* error) {
    332   ThreadRestrictions::AssertIOAllowed();
    333 
    334   // If the path exists, we've succeeded if it's a directory, failed otherwise.
    335   const wchar_t* full_path_str = full_path.value().c_str();
    336   DWORD fileattr = ::GetFileAttributes(full_path_str);
    337   if (fileattr != INVALID_FILE_ATTRIBUTES) {
    338     if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
    339       DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
    340                << "directory already exists.";
    341       return true;
    342     }
    343     DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
    344                   << "conflicts with existing file.";
    345     if (error) {
    346       *error = PLATFORM_FILE_ERROR_NOT_A_DIRECTORY;
    347     }
    348     return false;
    349   }
    350 
    351   // Invariant:  Path does not exist as file or directory.
    352 
    353   // Attempt to create the parent recursively.  This will immediately return
    354   // true if it already exists, otherwise will create all required parent
    355   // directories starting with the highest-level missing parent.
    356   FilePath parent_path(full_path.DirName());
    357   if (parent_path.value() == full_path.value()) {
    358     if (error) {
    359       *error = PLATFORM_FILE_ERROR_NOT_FOUND;
    360     }
    361     return false;
    362   }
    363   if (!CreateDirectoryAndGetError(parent_path, error)) {
    364     DLOG(WARNING) << "Failed to create one of the parent directories.";
    365     if (error) {
    366       DCHECK(*error != PLATFORM_FILE_OK);
    367     }
    368     return false;
    369   }
    370 
    371   if (!::CreateDirectory(full_path_str, NULL)) {
    372     DWORD error_code = ::GetLastError();
    373     if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
    374       // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
    375       // were racing with someone creating the same directory, or a file
    376       // with the same path.  If DirectoryExists() returns true, we lost the
    377       // race to create the same directory.
    378       return true;
    379     } else {
    380       if (error)
    381         *error = LastErrorToPlatformFileError(error_code);
    382       DLOG(WARNING) << "Failed to create directory " << full_path_str
    383                     << ", last error is " << error_code << ".";
    384       return false;
    385     }
    386   } else {
    387     return true;
    388   }
    389 }
    390 
    391 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
    392   ThreadRestrictions::AssertIOAllowed();
    393   FilePath mapped_file;
    394   if (!NormalizeToNativeFilePath(path, &mapped_file))
    395     return false;
    396   // NormalizeToNativeFilePath() will return a path that starts with
    397   // "\Device\Harddisk...".  Helper DevicePathToDriveLetterPath()
    398   // will find a drive letter which maps to the path's device, so
    399   // that we return a path starting with a drive letter.
    400   return DevicePathToDriveLetterPath(mapped_file, real_path);
    401 }
    402 
    403 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
    404                                  FilePath* out_drive_letter_path) {
    405   ThreadRestrictions::AssertIOAllowed();
    406 
    407   // Get the mapping of drive letters to device paths.
    408   const int kDriveMappingSize = 1024;
    409   wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
    410   if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
    411     DLOG(ERROR) << "Failed to get drive mapping.";
    412     return false;
    413   }
    414 
    415   // The drive mapping is a sequence of null terminated strings.
    416   // The last string is empty.
    417   wchar_t* drive_map_ptr = drive_mapping;
    418   wchar_t device_path_as_string[MAX_PATH];
    419   wchar_t drive[] = L" :";
    420 
    421   // For each string in the drive mapping, get the junction that links
    422   // to it.  If that junction is a prefix of |device_path|, then we
    423   // know that |drive| is the real path prefix.
    424   while (*drive_map_ptr) {
    425     drive[0] = drive_map_ptr[0];  // Copy the drive letter.
    426 
    427     if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
    428       FilePath device_path(device_path_as_string);
    429       if (device_path == nt_device_path ||
    430           device_path.IsParent(nt_device_path)) {
    431         *out_drive_letter_path = FilePath(drive +
    432             nt_device_path.value().substr(wcslen(device_path_as_string)));
    433         return true;
    434       }
    435     }
    436     // Move to the next drive letter string, which starts one
    437     // increment after the '\0' that terminates the current string.
    438     while (*drive_map_ptr++);
    439   }
    440 
    441   // No drive matched.  The path does not start with a device junction
    442   // that is mounted as a drive letter.  This means there is no drive
    443   // letter path to the volume that holds |device_path|, so fail.
    444   return false;
    445 }
    446 
    447 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
    448   ThreadRestrictions::AssertIOAllowed();
    449   // In Vista, GetFinalPathNameByHandle() would give us the real path
    450   // from a file handle.  If we ever deprecate XP, consider changing the
    451   // code below to a call to GetFinalPathNameByHandle().  The method this
    452   // function uses is explained in the following msdn article:
    453   // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
    454   base::win::ScopedHandle file_handle(
    455       ::CreateFile(path.value().c_str(),
    456                    GENERIC_READ,
    457                    kFileShareAll,
    458                    NULL,
    459                    OPEN_EXISTING,
    460                    FILE_ATTRIBUTE_NORMAL,
    461                    NULL));
    462   if (!file_handle)
    463     return false;
    464 
    465   // Create a file mapping object.  Can't easily use MemoryMappedFile, because
    466   // we only map the first byte, and need direct access to the handle. You can
    467   // not map an empty file, this call fails in that case.
    468   base::win::ScopedHandle file_map_handle(
    469       ::CreateFileMapping(file_handle.Get(),
    470                           NULL,
    471                           PAGE_READONLY,
    472                           0,
    473                           1,  // Just one byte.  No need to look at the data.
    474                           NULL));
    475   if (!file_map_handle)
    476     return false;
    477 
    478   // Use a view of the file to get the path to the file.
    479   void* file_view = MapViewOfFile(file_map_handle.Get(),
    480                                   FILE_MAP_READ, 0, 0, 1);
    481   if (!file_view)
    482     return false;
    483 
    484   // The expansion of |path| into a full path may make it longer.
    485   // GetMappedFileName() will fail if the result is longer than MAX_PATH.
    486   // Pad a bit to be safe.  If kMaxPathLength is ever changed to be less
    487   // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
    488   // not return kMaxPathLength.  This would mean that only part of the
    489   // path fit in |mapped_file_path|.
    490   const int kMaxPathLength = MAX_PATH + 10;
    491   wchar_t mapped_file_path[kMaxPathLength];
    492   bool success = false;
    493   HANDLE cp = GetCurrentProcess();
    494   if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
    495     *nt_path = FilePath(mapped_file_path);
    496     success = true;
    497   }
    498   ::UnmapViewOfFile(file_view);
    499   return success;
    500 }
    501 
    502 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
    503 // them if we do decide to.
    504 bool IsLink(const FilePath& file_path) {
    505   return false;
    506 }
    507 
    508 bool GetFileInfo(const FilePath& file_path, PlatformFileInfo* results) {
    509   ThreadRestrictions::AssertIOAllowed();
    510 
    511   WIN32_FILE_ATTRIBUTE_DATA attr;
    512   if (!GetFileAttributesEx(file_path.value().c_str(),
    513                            GetFileExInfoStandard, &attr)) {
    514     return false;
    515   }
    516 
    517   ULARGE_INTEGER size;
    518   size.HighPart = attr.nFileSizeHigh;
    519   size.LowPart = attr.nFileSizeLow;
    520   results->size = size.QuadPart;
    521 
    522   results->is_directory =
    523       (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
    524   results->last_modified = Time::FromFileTime(attr.ftLastWriteTime);
    525   results->last_accessed = Time::FromFileTime(attr.ftLastAccessTime);
    526   results->creation_time = Time::FromFileTime(attr.ftCreationTime);
    527 
    528   return true;
    529 }
    530 
    531 FILE* OpenFile(const FilePath& filename, const char* mode) {
    532   ThreadRestrictions::AssertIOAllowed();
    533   std::wstring w_mode = ASCIIToWide(std::string(mode));
    534   return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
    535 }
    536 
    537 int ReadFile(const FilePath& filename, char* data, int size) {
    538   ThreadRestrictions::AssertIOAllowed();
    539   base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
    540                                           GENERIC_READ,
    541                                           FILE_SHARE_READ | FILE_SHARE_WRITE,
    542                                           NULL,
    543                                           OPEN_EXISTING,
    544                                           FILE_FLAG_SEQUENTIAL_SCAN,
    545                                           NULL));
    546   if (!file)
    547     return -1;
    548 
    549   DWORD read;
    550   if (::ReadFile(file, data, size, &read, NULL) &&
    551       static_cast<int>(read) == size)
    552     return read;
    553   return -1;
    554 }
    555 
    556 }  // namespace base
    557 
    558 // -----------------------------------------------------------------------------
    559 
    560 namespace file_util {
    561 
    562 using base::DirectoryExists;
    563 using base::FilePath;
    564 using base::kFileShareAll;
    565 
    566 FILE* OpenFile(const std::string& filename, const char* mode) {
    567   base::ThreadRestrictions::AssertIOAllowed();
    568   return _fsopen(filename.c_str(), mode, _SH_DENYNO);
    569 }
    570 
    571 int WriteFile(const FilePath& filename, const char* data, int size) {
    572   base::ThreadRestrictions::AssertIOAllowed();
    573   base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
    574                                           GENERIC_WRITE,
    575                                           0,
    576                                           NULL,
    577                                           CREATE_ALWAYS,
    578                                           0,
    579                                           NULL));
    580   if (!file) {
    581     DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
    582                                << filename.value();
    583     return -1;
    584   }
    585 
    586   DWORD written;
    587   BOOL result = ::WriteFile(file, data, size, &written, NULL);
    588   if (result && static_cast<int>(written) == size)
    589     return written;
    590 
    591   if (!result) {
    592     // WriteFile failed.
    593     DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value()
    594                                << " failed";
    595   } else {
    596     // Didn't write all the bytes.
    597     DLOG(WARNING) << "wrote" << written << " bytes to "
    598                   << filename.value() << " expected " << size;
    599   }
    600   return -1;
    601 }
    602 
    603 int AppendToFile(const FilePath& filename, const char* data, int size) {
    604   base::ThreadRestrictions::AssertIOAllowed();
    605   base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
    606                                           FILE_APPEND_DATA,
    607                                           0,
    608                                           NULL,
    609                                           OPEN_EXISTING,
    610                                           0,
    611                                           NULL));
    612   if (!file) {
    613     DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path "
    614                                << filename.value();
    615     return -1;
    616   }
    617 
    618   DWORD written;
    619   BOOL result = ::WriteFile(file, data, size, &written, NULL);
    620   if (result && static_cast<int>(written) == size)
    621     return written;
    622 
    623   if (!result) {
    624     // WriteFile failed.
    625     DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value()
    626                                << " failed";
    627   } else {
    628     // Didn't write all the bytes.
    629     DLOG(WARNING) << "wrote" << written << " bytes to "
    630                   << filename.value() << " expected " << size;
    631   }
    632   return -1;
    633 }
    634 
    635 // Gets the current working directory for the process.
    636 bool GetCurrentDirectory(FilePath* dir) {
    637   base::ThreadRestrictions::AssertIOAllowed();
    638 
    639   wchar_t system_buffer[MAX_PATH];
    640   system_buffer[0] = 0;
    641   DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
    642   if (len == 0 || len > MAX_PATH)
    643     return false;
    644   // TODO(evanm): the old behavior of this function was to always strip the
    645   // trailing slash.  We duplicate this here, but it shouldn't be necessary
    646   // when everyone is using the appropriate FilePath APIs.
    647   std::wstring dir_str(system_buffer);
    648   *dir = FilePath(dir_str).StripTrailingSeparators();
    649   return true;
    650 }
    651 
    652 // Sets the current working directory for the process.
    653 bool SetCurrentDirectory(const FilePath& directory) {
    654   base::ThreadRestrictions::AssertIOAllowed();
    655   BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
    656   return ret != 0;
    657 }
    658 
    659 int GetMaximumPathComponentLength(const FilePath& path) {
    660   base::ThreadRestrictions::AssertIOAllowed();
    661 
    662   wchar_t volume_path[MAX_PATH];
    663   if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
    664                           volume_path,
    665                           arraysize(volume_path))) {
    666     return -1;
    667   }
    668 
    669   DWORD max_length = 0;
    670   if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
    671                              NULL, 0)) {
    672     return -1;
    673   }
    674 
    675   // Length of |path| with path separator appended.
    676   size_t prefix = path.StripTrailingSeparators().value().size() + 1;
    677   // The whole path string must be shorter than MAX_PATH. That is, it must be
    678   // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
    679   int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
    680   return std::min(whole_path_limit, static_cast<int>(max_length));
    681 }
    682 
    683 }  // namespace file_util
    684 
    685 namespace base {
    686 namespace internal {
    687 
    688 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
    689   ThreadRestrictions::AssertIOAllowed();
    690 
    691   // NOTE: I suspect we could support longer paths, but that would involve
    692   // analyzing all our usage of files.
    693   if (from_path.value().length() >= MAX_PATH ||
    694       to_path.value().length() >= MAX_PATH) {
    695     return false;
    696   }
    697   if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
    698                  MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
    699     return true;
    700 
    701   // Keep the last error value from MoveFileEx around in case the below
    702   // fails.
    703   bool ret = false;
    704   DWORD last_error = ::GetLastError();
    705 
    706   if (DirectoryExists(from_path)) {
    707     // MoveFileEx fails if moving directory across volumes. We will simulate
    708     // the move by using Copy and Delete. Ideally we could check whether
    709     // from_path and to_path are indeed in different volumes.
    710     ret = internal::CopyAndDeleteDirectory(from_path, to_path);
    711   }
    712 
    713   if (!ret) {
    714     // Leave a clue about what went wrong so that it can be (at least) picked
    715     // up by a PLOG entry.
    716     ::SetLastError(last_error);
    717   }
    718 
    719   return ret;
    720 }
    721 
    722 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
    723   ThreadRestrictions::AssertIOAllowed();
    724 
    725   // NOTE: I suspect we could support longer paths, but that would involve
    726   // analyzing all our usage of files.
    727   if (from_path.value().length() >= MAX_PATH ||
    728       to_path.value().length() >= MAX_PATH) {
    729     return false;
    730   }
    731   return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
    732                      false) != 0);
    733 }
    734 
    735 bool CopyAndDeleteDirectory(const FilePath& from_path,
    736                             const FilePath& to_path) {
    737   ThreadRestrictions::AssertIOAllowed();
    738   if (CopyDirectory(from_path, to_path, true)) {
    739     if (DeleteFile(from_path, true))
    740       return true;
    741 
    742     // Like Move, this function is not transactional, so we just
    743     // leave the copied bits behind if deleting from_path fails.
    744     // If to_path exists previously then we have already overwritten
    745     // it by now, we don't get better off by deleting the new bits.
    746   }
    747   return false;
    748 }
    749 
    750 }  // namespace internal
    751 }  // namespace base
    752