• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/files/file_util.h"
6 
7 // windows.h includes winsock.h which isn't compatible with winsock2.h. To use winsock2.h
8 // you have to include it first.
9 #include <winsock2.h>
10 #include <windows.h>
11 
12 #include <io.h>
13 #include <psapi.h>
14 #include <share.h>
15 #include <shellapi.h>
16 #include <shlobj.h>
17 #include <stddef.h>
18 #include <stdint.h>
19 #include <time.h>
20 
21 #include <algorithm>
22 #include <iterator>
23 #include <limits>
24 #include <string>
25 #include <string_view>
26 
27 #include "base/files/file_enumerator.h"
28 #include "base/files/file_path.h"
29 #include "base/logging.h"
30 #include "base/macros.h"
31 #include "base/strings/string_number_conversions.h"
32 #include "base/strings/string_util.h"
33 #include "base/strings/stringprintf.h"
34 #include "base/strings/utf_string_conversions.h"
35 #include "base/win/scoped_handle.h"
36 #include "base/win/win_util.h"
37 
38 // #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036.  See the
39 // "Community Additions" comment on MSDN here:
40 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx
41 #define SystemFunction036 NTAPI SystemFunction036
42 #include <ntsecapi.h>
43 #undef SystemFunction036
44 
45 namespace base {
46 
47 namespace {
48 
49 const DWORD kFileShareAll =
50     FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
51 
52 // Deletes all files and directories in a path.
53 // Returns ERROR_SUCCESS on success or the Windows error code corresponding to
54 // the first error encountered.
DeleteFileRecursive(const FilePath & path,const FilePath::StringType & pattern,bool recursive)55 DWORD DeleteFileRecursive(const FilePath& path,
56                           const FilePath::StringType& pattern,
57                           bool recursive) {
58   FileEnumerator traversal(path, false,
59                            FileEnumerator::FILES | FileEnumerator::DIRECTORIES,
60                            pattern);
61   DWORD result = ERROR_SUCCESS;
62   for (FilePath current = traversal.Next(); !current.empty();
63        current = traversal.Next()) {
64     // Try to clear the read-only bit if we find it.
65     FileEnumerator::FileInfo info = traversal.GetInfo();
66     if ((info.find_data().dwFileAttributes & FILE_ATTRIBUTE_READONLY) &&
67         (recursive || !info.IsDirectory())) {
68       ::SetFileAttributes(
69           ToWCharT(&current.value()),
70           info.find_data().dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
71     }
72 
73     DWORD this_result = ERROR_SUCCESS;
74     if (info.IsDirectory()) {
75       if (recursive) {
76         this_result = DeleteFileRecursive(current, pattern, true);
77         if (this_result == ERROR_SUCCESS &&
78             !::RemoveDirectory(ToWCharT(&current.value()))) {
79           this_result = ::GetLastError();
80         }
81       }
82     } else if (!::DeleteFile(ToWCharT(&current.value()))) {
83       this_result = ::GetLastError();
84     }
85     if (result == ERROR_SUCCESS)
86       result = this_result;
87   }
88   return result;
89 }
90 
91 // Appends |mode_char| to |mode| before the optional character set encoding; see
92 // https://msdn.microsoft.com/library/yeby3zcb.aspx for details.
AppendModeCharacter(char16_t mode_char,std::u16string * mode)93 void AppendModeCharacter(char16_t mode_char, std::u16string* mode) {
94   size_t comma_pos = mode->find(L',');
95   mode->insert(comma_pos == std::u16string::npos ? mode->length() : comma_pos,
96                1, mode_char);
97 }
98 
99 // Returns ERROR_SUCCESS on success, or a Windows error code on failure.
DoDeleteFile(const FilePath & path,bool recursive)100 DWORD DoDeleteFile(const FilePath& path, bool recursive) {
101   if (path.empty())
102     return ERROR_SUCCESS;
103 
104   if (path.value().length() >= MAX_PATH)
105     return ERROR_BAD_PATHNAME;
106 
107   // Handle any path with wildcards.
108   if (path.BaseName().value().find_first_of(u"*?") !=
109       FilePath::StringType::npos) {
110     return DeleteFileRecursive(path.DirName(), path.BaseName().value(),
111                                recursive);
112   }
113 
114   // Report success if the file or path does not exist.
115   const DWORD attr = ::GetFileAttributes(ToWCharT(&path.value()));
116   if (attr == INVALID_FILE_ATTRIBUTES) {
117     const DWORD error_code = ::GetLastError();
118     return (error_code == ERROR_FILE_NOT_FOUND ||
119             error_code == ERROR_PATH_NOT_FOUND)
120                ? ERROR_SUCCESS
121                : error_code;
122   }
123 
124   // Clear the read-only bit if it is set.
125   if ((attr & FILE_ATTRIBUTE_READONLY) &&
126       !::SetFileAttributes(ToWCharT(&path.value()),
127                            attr & ~FILE_ATTRIBUTE_READONLY)) {
128     return ::GetLastError();
129   }
130 
131   // Perform a simple delete on anything that isn't a directory.
132   if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
133     return ::DeleteFile(ToWCharT(&path.value())) ? ERROR_SUCCESS
134                                                  : ::GetLastError();
135   }
136 
137   if (recursive) {
138     const DWORD error_code = DeleteFileRecursive(path, u"*", true);
139     if (error_code != ERROR_SUCCESS)
140       return error_code;
141   }
142   return ::RemoveDirectory(ToWCharT(&path.value())) ? ERROR_SUCCESS
143                                                     : ::GetLastError();
144 }
145 
RandomDataToGUIDString(const uint64_t bytes[2])146 std::string RandomDataToGUIDString(const uint64_t bytes[2]) {
147   return base::StringPrintf(
148       "%08x-%04x-%04x-%04x-%012llx", static_cast<unsigned int>(bytes[0] >> 32),
149       static_cast<unsigned int>((bytes[0] >> 16) & 0x0000ffff),
150       static_cast<unsigned int>(bytes[0] & 0x0000ffff),
151       static_cast<unsigned int>(bytes[1] >> 48),
152       bytes[1] & 0x0000ffff'ffffffffULL);
153 }
154 
RandBytes(void * output,size_t output_length)155 void RandBytes(void* output, size_t output_length) {
156   char* output_ptr = static_cast<char*>(output);
157   while (output_length > 0) {
158     const ULONG output_bytes_this_pass = static_cast<ULONG>(std::min(
159         output_length, static_cast<size_t>(std::numeric_limits<ULONG>::max())));
160     const bool success =
161         RtlGenRandom(output_ptr, output_bytes_this_pass) != FALSE;
162     CHECK(success);
163     output_length -= output_bytes_this_pass;
164     output_ptr += output_bytes_this_pass;
165   }
166 }
167 
GenerateGUID()168 std::string GenerateGUID() {
169   uint64_t sixteen_bytes[2];
170   // Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
171   // base version directly, and to prevent the dependency from base/ to crypto/.
172   RandBytes(&sixteen_bytes, sizeof(sixteen_bytes));
173 
174   // Set the GUID to version 4 as described in RFC 4122, section 4.4.
175   // The format of GUID version 4 must be xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
176   // where y is one of [8, 9, A, B].
177 
178   // Clear the version bits and set the version to 4:
179   sixteen_bytes[0] &= 0xffffffff'ffff0fffULL;
180   sixteen_bytes[0] |= 0x00000000'00004000ULL;
181 
182   // Set the two most significant bits (bits 6 and 7) of the
183   // clock_seq_hi_and_reserved to zero and one, respectively:
184   sixteen_bytes[1] &= 0x3fffffff'ffffffffULL;
185   sixteen_bytes[1] |= 0x80000000'00000000ULL;
186 
187   return RandomDataToGUIDString(sixteen_bytes);
188 }
189 
190 }  // namespace
191 
MakeAbsoluteFilePath(const FilePath & input)192 FilePath MakeAbsoluteFilePath(const FilePath& input) {
193   char16_t file_path[MAX_PATH];
194   if (!_wfullpath(ToWCharT(file_path), ToWCharT(&input.value()), MAX_PATH))
195     return FilePath();
196   return FilePath(file_path);
197 }
198 
DeleteFile(const FilePath & path,bool recursive)199 bool DeleteFile(const FilePath& path, bool recursive) {
200   static constexpr char kRecursive[] = "DeleteFile.Recursive";
201   static constexpr char kNonRecursive[] = "DeleteFile.NonRecursive";
202   const std::string_view operation(recursive ? kRecursive : kNonRecursive);
203 
204   // Metrics for delete failures tracked in https://crbug.com/599084. Delete may
205   // fail for a number of reasons. Log some metrics relating to failures in the
206   // current code so that any improvements or regressions resulting from
207   // subsequent code changes can be detected.
208   const DWORD error = DoDeleteFile(path, recursive);
209   return error == ERROR_SUCCESS;
210 }
211 
DeleteFileAfterReboot(const FilePath & path)212 bool DeleteFileAfterReboot(const FilePath& path) {
213   if (path.value().length() >= MAX_PATH)
214     return false;
215 
216   return MoveFileEx(ToWCharT(&path.value()), NULL,
217                     MOVEFILE_DELAY_UNTIL_REBOOT | MOVEFILE_REPLACE_EXISTING) !=
218          FALSE;
219 }
220 
ReplaceFile(const FilePath & from_path,const FilePath & to_path,File::Error * error)221 bool ReplaceFile(const FilePath& from_path,
222                  const FilePath& to_path,
223                  File::Error* error) {
224   // Try a simple move first.  It will only succeed when |to_path| doesn't
225   // already exist.
226   if (::MoveFile(ToWCharT(&from_path.value()), ToWCharT(&to_path.value())))
227     return true;
228   File::Error move_error = File::OSErrorToFileError(GetLastError());
229 
230   // Try the full-blown replace if the move fails, as ReplaceFile will only
231   // succeed when |to_path| does exist. When writing to a network share, we may
232   // not be able to change the ACLs. Ignore ACL errors then
233   // (REPLACEFILE_IGNORE_MERGE_ERRORS).
234   if (::ReplaceFile(ToWCharT(&to_path.value()), ToWCharT(&from_path.value()),
235                     NULL, REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
236     return true;
237   }
238   // In the case of FILE_ERROR_NOT_FOUND from ReplaceFile, it is likely that
239   // |to_path| does not exist. In this case, the more relevant error comes
240   // from the call to MoveFile.
241   if (error) {
242     File::Error replace_error = File::OSErrorToFileError(GetLastError());
243     *error = replace_error == File::FILE_ERROR_NOT_FOUND ? move_error
244                                                          : replace_error;
245   }
246   return false;
247 }
248 
PathExists(const FilePath & path)249 bool PathExists(const FilePath& path) {
250   return (GetFileAttributes(ToWCharT(&path.value())) !=
251           INVALID_FILE_ATTRIBUTES);
252 }
253 
PathIsWritable(const FilePath & path)254 bool PathIsWritable(const FilePath& path) {
255   HANDLE dir =
256       CreateFile(ToWCharT(&path.value()), FILE_ADD_FILE, kFileShareAll, NULL,
257                  OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
258 
259   if (dir == INVALID_HANDLE_VALUE)
260     return false;
261 
262   CloseHandle(dir);
263   return true;
264 }
265 
DirectoryExists(const FilePath & path)266 bool DirectoryExists(const FilePath& path) {
267   DWORD fileattr = GetFileAttributes(ToWCharT(&path.value()));
268   if (fileattr != INVALID_FILE_ATTRIBUTES)
269     return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
270   return false;
271 }
272 
GetTempDir(FilePath * path)273 bool GetTempDir(FilePath* path) {
274   char16_t temp_path[MAX_PATH + 1];
275   DWORD path_len = ::GetTempPath(MAX_PATH, ToWCharT(temp_path));
276   if (path_len >= MAX_PATH || path_len <= 0)
277     return false;
278   // TODO(evanm): the old behavior of this function was to always strip the
279   // trailing slash.  We duplicate this here, but it shouldn't be necessary
280   // when everyone is using the appropriate FilePath APIs.
281   *path = FilePath(temp_path).StripTrailingSeparators();
282   return true;
283 }
284 
CreateTemporaryDirInDir(const FilePath & base_dir,const FilePath::StringType & prefix,FilePath * new_dir)285 bool CreateTemporaryDirInDir(const FilePath& base_dir,
286                              const FilePath::StringType& prefix,
287                              FilePath* new_dir) {
288   FilePath path_to_create;
289 
290   for (int count = 0; count < 50; ++count) {
291     // Try create a new temporary directory with random generated name. If
292     // the one exists, keep trying another path name until we reach some limit.
293     std::u16string new_dir_name;
294     new_dir_name.assign(prefix);
295     new_dir_name.append(IntToString16(::GetCurrentProcessId()));
296     new_dir_name.push_back('_');
297     new_dir_name.append(UTF8ToUTF16(GenerateGUID()));
298 
299     path_to_create = base_dir.Append(new_dir_name);
300     if (::CreateDirectory(ToWCharT(&path_to_create.value()), NULL)) {
301       *new_dir = path_to_create;
302       return true;
303     }
304   }
305 
306   return false;
307 }
308 
CreateNewTempDirectory(const FilePath::StringType & prefix,FilePath * new_temp_path)309 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
310                             FilePath* new_temp_path) {
311   FilePath system_temp_dir;
312   if (!GetTempDir(&system_temp_dir))
313     return false;
314 
315   return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
316 }
317 
CreateDirectoryAndGetError(const FilePath & full_path,File::Error * error)318 bool CreateDirectoryAndGetError(const FilePath& full_path, File::Error* error) {
319   // If the path exists, we've succeeded if it's a directory, failed otherwise.
320   DWORD fileattr = ::GetFileAttributes(ToWCharT(&full_path.value()));
321   if (fileattr != INVALID_FILE_ATTRIBUTES) {
322     if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
323       return true;
324     }
325     DLOG(WARNING) << "CreateDirectory(" << UTF16ToUTF8(full_path.value())
326                   << "), "
327                   << "conflicts with existing file.";
328     if (error) {
329       *error = File::FILE_ERROR_NOT_A_DIRECTORY;
330     }
331     return false;
332   }
333 
334   // Invariant:  Path does not exist as file or directory.
335 
336   // Attempt to create the parent recursively.  This will immediately return
337   // true if it already exists, otherwise will create all required parent
338   // directories starting with the highest-level missing parent.
339   FilePath parent_path(full_path.DirName());
340   if (parent_path.value() == full_path.value()) {
341     if (error) {
342       *error = File::FILE_ERROR_NOT_FOUND;
343     }
344     return false;
345   }
346   if (!CreateDirectoryAndGetError(parent_path, error)) {
347     DLOG(WARNING) << "Failed to create one of the parent directories.";
348     if (error) {
349       DCHECK(*error != File::FILE_OK);
350     }
351     return false;
352   }
353 
354   if (!::CreateDirectory(ToWCharT(&full_path.value()), NULL)) {
355     DWORD error_code = ::GetLastError();
356     if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
357       // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
358       // were racing with someone creating the same directory, or a file
359       // with the same path.  If DirectoryExists() returns true, we lost the
360       // race to create the same directory.
361       return true;
362     } else {
363       if (error)
364         *error = File::OSErrorToFileError(error_code);
365       DLOG(WARNING) << "Failed to create directory "
366                     << UTF16ToUTF8(full_path.value()) << ", last error is "
367                     << error_code << ".";
368       return false;
369     }
370   } else {
371     return true;
372   }
373 }
374 
NormalizeFilePath(const FilePath & path,FilePath * real_path)375 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
376   FilePath mapped_file;
377   if (!NormalizeToNativeFilePath(path, &mapped_file))
378     return false;
379   // NormalizeToNativeFilePath() will return a path that starts with
380   // "\Device\Harddisk...".  Helper DevicePathToDriveLetterPath()
381   // will find a drive letter which maps to the path's device, so
382   // that we return a path starting with a drive letter.
383   return DevicePathToDriveLetterPath(mapped_file, real_path);
384 }
385 
DevicePathToDriveLetterPath(const FilePath & nt_device_path,FilePath * out_drive_letter_path)386 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
387                                  FilePath* out_drive_letter_path) {
388   // Get the mapping of drive letters to device paths.
389   const int kDriveMappingSize = 1024;
390   char16_t drive_mapping[kDriveMappingSize] = {'\0'};
391   if (!::GetLogicalDriveStrings(kDriveMappingSize - 1,
392                                 ToWCharT(drive_mapping))) {
393     DLOG(ERROR) << "Failed to get drive mapping.";
394     return false;
395   }
396 
397   // The drive mapping is a sequence of null terminated strings.
398   // The last string is empty.
399   char16_t* drive_map_ptr = drive_mapping;
400   char16_t device_path_as_string[MAX_PATH];
401   char16_t drive[] = u" :";
402 
403   // For each string in the drive mapping, get the junction that links
404   // to it.  If that junction is a prefix of |device_path|, then we
405   // know that |drive| is the real path prefix.
406   while (*drive_map_ptr) {
407     drive[0] = drive_map_ptr[0];  // Copy the drive letter.
408 
409     if (QueryDosDevice(ToWCharT(drive), ToWCharT(device_path_as_string),
410                        MAX_PATH)) {
411       FilePath device_path(device_path_as_string);
412       if (device_path == nt_device_path ||
413           device_path.IsParent(nt_device_path)) {
414         *out_drive_letter_path =
415             FilePath(drive + nt_device_path.value().substr(
416                                  wcslen(ToWCharT(device_path_as_string))));
417         return true;
418       }
419     }
420     // Move to the next drive letter string, which starts one
421     // increment after the '\0' that terminates the current string.
422     while (*drive_map_ptr++) {
423     }
424   }
425 
426   // No drive matched.  The path does not start with a device junction
427   // that is mounted as a drive letter.  This means there is no drive
428   // letter path to the volume that holds |device_path|, so fail.
429   return false;
430 }
431 
NormalizeToNativeFilePath(const FilePath & path,FilePath * nt_path)432 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
433   // In Vista, GetFinalPathNameByHandle() would give us the real path
434   // from a file handle.  If we ever deprecate XP, consider changing the
435   // code below to a call to GetFinalPathNameByHandle().  The method this
436   // function uses is explained in the following msdn article:
437   // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
438   win::ScopedHandle file_handle(
439       ::CreateFile(ToWCharT(&path.value()), GENERIC_READ, kFileShareAll, NULL,
440                    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
441   if (!file_handle.IsValid())
442     return false;
443 
444   // Create a file mapping object.  Can't easily use MemoryMappedFile, because
445   // we only map the first byte, and need direct access to the handle. You can
446   // not map an empty file, this call fails in that case.
447   win::ScopedHandle file_map_handle(
448       ::CreateFileMapping(file_handle.Get(), NULL, PAGE_READONLY, 0,
449                           1,  // Just one byte.  No need to look at the data.
450                           NULL));
451   if (!file_map_handle.IsValid())
452     return false;
453 
454   // Use a view of the file to get the path to the file.
455   void* file_view =
456       MapViewOfFile(file_map_handle.Get(), FILE_MAP_READ, 0, 0, 1);
457   if (!file_view)
458     return false;
459 
460   // The expansion of |path| into a full path may make it longer.
461   // GetMappedFileName() will fail if the result is longer than MAX_PATH.
462   // Pad a bit to be safe.  If kMaxPathLength is ever changed to be less
463   // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
464   // not return kMaxPathLength.  This would mean that only part of the
465   // path fit in |mapped_file_path|.
466   const int kMaxPathLength = MAX_PATH + 10;
467   char16_t mapped_file_path[kMaxPathLength];
468   bool success = false;
469   HANDLE cp = GetCurrentProcess();
470   if (::GetMappedFileNameW(cp, file_view, ToWCharT(mapped_file_path),
471                            kMaxPathLength)) {
472     *nt_path = FilePath(mapped_file_path);
473     success = true;
474   }
475   ::UnmapViewOfFile(file_view);
476   return success;
477 }
478 
479 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
480 // them if we do decide to.
IsLink(const FilePath & file_path)481 bool IsLink(const FilePath& file_path) {
482   return false;
483 }
484 
GetFileInfo(const FilePath & file_path,File::Info * results)485 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
486   WIN32_FILE_ATTRIBUTE_DATA attr;
487   if (!GetFileAttributesEx(ToWCharT(&file_path.value()), GetFileExInfoStandard,
488                            &attr)) {
489     return false;
490   }
491 
492   ULARGE_INTEGER size;
493   size.HighPart = attr.nFileSizeHigh;
494   size.LowPart = attr.nFileSizeLow;
495   results->size = size.QuadPart;
496 
497   results->is_directory =
498       (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
499   results->last_modified = *reinterpret_cast<uint64_t*>(&attr.ftLastWriteTime);
500   results->last_accessed = *reinterpret_cast<uint64_t*>(&attr.ftLastAccessTime);
501   results->creation_time = *reinterpret_cast<uint64_t*>(&attr.ftCreationTime);
502 
503   return true;
504 }
505 
OpenFile(const FilePath & filename,const char * mode)506 FILE* OpenFile(const FilePath& filename, const char* mode) {
507   // 'N' is unconditionally added below, so be sure there is not one already
508   // present before a comma in |mode|.
509   DCHECK(
510       strchr(mode, 'N') == nullptr ||
511       (strchr(mode, ',') != nullptr && strchr(mode, 'N') > strchr(mode, ',')));
512   std::u16string w_mode = ASCIIToUTF16(mode);
513   AppendModeCharacter(L'N', &w_mode);
514   return _wfsopen(ToWCharT(&filename.value()), ToWCharT(&w_mode), _SH_DENYNO);
515 }
516 
FileToFILE(File file,const char * mode)517 FILE* FileToFILE(File file, const char* mode) {
518   if (!file.IsValid())
519     return NULL;
520   int fd =
521       _open_osfhandle(reinterpret_cast<intptr_t>(file.GetPlatformFile()), 0);
522   if (fd < 0)
523     return NULL;
524   file.TakePlatformFile();
525   FILE* stream = _fdopen(fd, mode);
526   if (!stream)
527     _close(fd);
528   return stream;
529 }
530 
ReadFile(const FilePath & filename,char * data,int max_size)531 int ReadFile(const FilePath& filename, char* data, int max_size) {
532   win::ScopedHandle file(CreateFile(ToWCharT(&filename.value()), GENERIC_READ,
533                                     FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
534                                     OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN,
535                                     NULL));
536   if (!file.IsValid())
537     return -1;
538 
539   DWORD read;
540   if (::ReadFile(file.Get(), data, max_size, &read, NULL))
541     return read;
542 
543   return -1;
544 }
545 
WriteFile(const FilePath & filename,const char * data,int size)546 int WriteFile(const FilePath& filename, const char* data, int size) {
547   win::ScopedHandle file(CreateFile(ToWCharT(&filename.value()), GENERIC_WRITE,
548                                     0, NULL, CREATE_ALWAYS,
549                                     FILE_ATTRIBUTE_NORMAL, NULL));
550   if (!file.IsValid()) {
551     DPLOG(WARNING) << "CreateFile failed for path "
552                    << UTF16ToUTF8(filename.value());
553     return -1;
554   }
555 
556   DWORD written;
557   BOOL result = ::WriteFile(file.Get(), data, size, &written, NULL);
558   if (result && static_cast<int>(written) == size)
559     return written;
560 
561   if (!result) {
562     // WriteFile failed.
563     DPLOG(WARNING) << "writing file " << UTF16ToUTF8(filename.value())
564                    << " failed";
565   } else {
566     // Didn't write all the bytes.
567     DLOG(WARNING) << "wrote" << written << " bytes to "
568                   << UTF16ToUTF8(filename.value()) << " expected " << size;
569   }
570   return -1;
571 }
572 
AppendToFile(const FilePath & filename,const char * data,int size)573 bool AppendToFile(const FilePath& filename, const char* data, int size) {
574   win::ScopedHandle file(CreateFile(ToWCharT(&filename.value()),
575                                     FILE_APPEND_DATA, 0, NULL, OPEN_EXISTING, 0,
576                                     NULL));
577   if (!file.IsValid()) {
578     return false;
579   }
580 
581   DWORD written;
582   BOOL result = ::WriteFile(file.Get(), data, size, &written, NULL);
583   if (result && static_cast<int>(written) == size)
584     return true;
585 
586   return false;
587 }
588 
GetCurrentDirectory(FilePath * dir)589 bool GetCurrentDirectory(FilePath* dir) {
590   char16_t system_buffer[MAX_PATH];
591   system_buffer[0] = 0;
592   DWORD len = ::GetCurrentDirectory(MAX_PATH, ToWCharT(system_buffer));
593   if (len == 0 || len > MAX_PATH)
594     return false;
595   // TODO(evanm): the old behavior of this function was to always strip the
596   // trailing slash.  We duplicate this here, but it shouldn't be necessary
597   // when everyone is using the appropriate FilePath APIs.
598   std::u16string dir_str(system_buffer);
599   *dir = FilePath(dir_str).StripTrailingSeparators();
600   return true;
601 }
602 
SetCurrentDirectory(const FilePath & directory)603 bool SetCurrentDirectory(const FilePath& directory) {
604   return ::SetCurrentDirectory(ToWCharT(&directory.value())) != 0;
605 }
606 
GetMaximumPathComponentLength(const FilePath & path)607 int GetMaximumPathComponentLength(const FilePath& path) {
608   char16_t volume_path[MAX_PATH];
609   if (!GetVolumePathNameW(ToWCharT(&path.NormalizePathSeparators().value()),
610                           ToWCharT(volume_path), std::size(volume_path))) {
611     return -1;
612   }
613 
614   DWORD max_length = 0;
615   if (!GetVolumeInformationW(ToWCharT(volume_path), NULL, 0, NULL, &max_length,
616                              NULL, NULL, 0)) {
617     return -1;
618   }
619 
620   // Length of |path| with path separator appended.
621   size_t prefix = path.StripTrailingSeparators().value().size() + 1;
622   // The whole path string must be shorter than MAX_PATH. That is, it must be
623   // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
624   int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
625   return std::min(whole_path_limit, static_cast<int>(max_length));
626 }
627 
SetNonBlocking(int fd)628 bool SetNonBlocking(int fd) {
629   unsigned long nonblocking = 1;
630   if (ioctlsocket(fd, FIONBIO, &nonblocking) == 0)
631     return true;
632   return false;
633 }
634 
635 }  // namespace base
636