Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2006-2008 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 <dirent.h>
      8 #include <errno.h>
      9 #include <fcntl.h>
     10 #include <fnmatch.h>
     11 #include <libgen.h>
     12 #include <stdio.h>
     13 #include <string.h>
     14 #include <sys/errno.h>
     15 #include <sys/mman.h>
     16 #include <sys/stat.h>
     17 #include <sys/types.h>
     18 #include <time.h>
     19 #include <unistd.h>
     20 
     21 #if defined(OS_MACOSX)
     22 #include <AvailabilityMacros.h>
     23 #endif
     24 
     25 #include <fstream>
     26 
     27 #include "base/basictypes.h"
     28 #include "base/eintr_wrapper.h"
     29 #include "base/file_path.h"
     30 #include "base/lock.h"
     31 #include "base/logging.h"
     32 #include "base/scoped_ptr.h"
     33 #include "base/singleton.h"
     34 #include "base/string_util.h"
     35 #include "base/sys_string_conversions.h"
     36 #include "base/time.h"
     37 #include "base/utf_string_conversions.h"
     38 
     39 namespace file_util {
     40 
     41 #if defined(OS_FREEBSD) || \
     42     (defined(OS_MACOSX) && \
     43      MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
     44 typedef struct stat stat_wrapper_t;
     45 static int CallStat(const char *path, stat_wrapper_t *sb) {
     46   return stat(path, sb);
     47 }
     48 #else
     49 typedef struct stat64 stat_wrapper_t;
     50 static int CallStat(const char *path, stat_wrapper_t *sb) {
     51   return stat64(path, sb);
     52 }
     53 #endif
     54 
     55 
     56 #if defined(GOOGLE_CHROME_BUILD)
     57 static const char* kTempFileName = "com.google.chrome.XXXXXX";
     58 #else
     59 static const char* kTempFileName = "org.chromium.XXXXXX";
     60 #endif
     61 
     62 std::wstring GetDirectoryFromPath(const std::wstring& path) {
     63   if (EndsWithSeparator(path)) {
     64     return FilePath::FromWStringHack(path)
     65         .StripTrailingSeparators()
     66         .ToWStringHack();
     67   } else {
     68     char full_path[PATH_MAX];
     69     base::strlcpy(full_path, WideToUTF8(path).c_str(), arraysize(full_path));
     70     return UTF8ToWide(dirname(full_path));
     71   }
     72 }
     73 
     74 bool AbsolutePath(FilePath* path) {
     75   char full_path[PATH_MAX];
     76   if (realpath(path->value().c_str(), full_path) == NULL)
     77     return false;
     78   *path = FilePath(full_path);
     79   return true;
     80 }
     81 
     82 int CountFilesCreatedAfter(const FilePath& path,
     83                            const base::Time& comparison_time) {
     84   int file_count = 0;
     85 
     86   DIR* dir = opendir(path.value().c_str());
     87   if (dir) {
     88 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_FREEBSD) && \
     89     !defined(OS_OPENBSD)
     90   #error Port warning: depending on the definition of struct dirent, \
     91          additional space for pathname may be needed
     92 #endif
     93     struct dirent ent_buf;
     94     struct dirent* ent;
     95     while (readdir_r(dir, &ent_buf, &ent) == 0 && ent) {
     96       if ((strcmp(ent->d_name, ".") == 0) ||
     97           (strcmp(ent->d_name, "..") == 0))
     98         continue;
     99 
    100       stat_wrapper_t st;
    101       int test = CallStat(path.Append(ent->d_name).value().c_str(), &st);
    102       if (test != 0) {
    103         PLOG(ERROR) << "stat64 failed";
    104         continue;
    105       }
    106       // Here, we use Time::TimeT(), which discards microseconds. This
    107       // means that files which are newer than |comparison_time| may
    108       // be considered older. If we don't discard microseconds, it
    109       // introduces another issue. Suppose the following case:
    110       //
    111       // 1. Get |comparison_time| by Time::Now() and the value is 10.1 (secs).
    112       // 2. Create a file and the current time is 10.3 (secs).
    113       //
    114       // As POSIX doesn't have microsecond precision for |st_ctime|,
    115       // the creation time of the file created in the step 2 is 10 and
    116       // the file is considered older than |comparison_time|. After
    117       // all, we may have to accept either of the two issues: 1. files
    118       // which are older than |comparison_time| are considered newer
    119       // (current implementation) 2. files newer than
    120       // |comparison_time| are considered older.
    121       if (st.st_ctime >= comparison_time.ToTimeT())
    122         ++file_count;
    123     }
    124     closedir(dir);
    125   }
    126   return file_count;
    127 }
    128 
    129 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
    130 // which works both with and without the recursive flag.  I'm not sure we need
    131 // that functionality. If not, remove from file_util_win.cc, otherwise add it
    132 // here.
    133 bool Delete(const FilePath& path, bool recursive) {
    134   const char* path_str = path.value().c_str();
    135   stat_wrapper_t file_info;
    136   int test = CallStat(path_str, &file_info);
    137   if (test != 0) {
    138     // The Windows version defines this condition as success.
    139     bool ret = (errno == ENOENT || errno == ENOTDIR);
    140     return ret;
    141   }
    142   if (!S_ISDIR(file_info.st_mode))
    143     return (unlink(path_str) == 0);
    144   if (!recursive)
    145     return (rmdir(path_str) == 0);
    146 
    147   bool success = true;
    148   std::stack<std::string> directories;
    149   directories.push(path.value());
    150   FileEnumerator traversal(path, true, static_cast<FileEnumerator::FILE_TYPE>(
    151         FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
    152         FileEnumerator::SHOW_SYM_LINKS));
    153   for (FilePath current = traversal.Next(); success && !current.empty();
    154        current = traversal.Next()) {
    155     FileEnumerator::FindInfo info;
    156     traversal.GetFindInfo(&info);
    157 
    158     if (S_ISDIR(info.stat.st_mode))
    159       directories.push(current.value());
    160     else
    161       success = (unlink(current.value().c_str()) == 0);
    162   }
    163 
    164   while (success && !directories.empty()) {
    165     FilePath dir = FilePath(directories.top());
    166     directories.pop();
    167     success = (rmdir(dir.value().c_str()) == 0);
    168   }
    169 
    170   return success;
    171 }
    172 
    173 bool Move(const FilePath& from_path, const FilePath& to_path) {
    174   // Windows compatibility: if to_path exists, from_path and to_path
    175   // must be the same type, either both files, or both directories.
    176   stat_wrapper_t to_file_info;
    177   if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
    178     stat_wrapper_t from_file_info;
    179     if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
    180       if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
    181         return false;
    182     } else {
    183       return false;
    184     }
    185   }
    186 
    187   if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
    188     return true;
    189 
    190   if (!CopyDirectory(from_path, to_path, true))
    191     return false;
    192 
    193   Delete(from_path, true);
    194   return true;
    195 }
    196 
    197 bool ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
    198   return (rename(from_path.value().c_str(), to_path.value().c_str()) == 0);
    199 }
    200 
    201 bool CopyDirectory(const FilePath& from_path,
    202                    const FilePath& to_path,
    203                    bool recursive) {
    204   // Some old callers of CopyDirectory want it to support wildcards.
    205   // After some discussion, we decided to fix those callers.
    206   // Break loudly here if anyone tries to do this.
    207   // TODO(evanm): remove this once we're sure it's ok.
    208   DCHECK(to_path.value().find('*') == std::string::npos);
    209   DCHECK(from_path.value().find('*') == std::string::npos);
    210 
    211   char top_dir[PATH_MAX];
    212   if (base::strlcpy(top_dir, from_path.value().c_str(),
    213                     arraysize(top_dir)) >= arraysize(top_dir)) {
    214     return false;
    215   }
    216 
    217   // This function does not properly handle destinations within the source
    218   FilePath real_to_path = to_path;
    219   if (PathExists(real_to_path)) {
    220     if (!AbsolutePath(&real_to_path))
    221       return false;
    222   } else {
    223     real_to_path = real_to_path.DirName();
    224     if (!AbsolutePath(&real_to_path))
    225       return false;
    226   }
    227   FilePath real_from_path = from_path;
    228   if (!AbsolutePath(&real_from_path))
    229     return false;
    230   if (real_to_path.value().size() >= real_from_path.value().size() &&
    231       real_to_path.value().compare(0, real_from_path.value().size(),
    232       real_from_path.value()) == 0)
    233     return false;
    234 
    235   bool success = true;
    236   FileEnumerator::FILE_TYPE traverse_type =
    237       static_cast<FileEnumerator::FILE_TYPE>(FileEnumerator::FILES |
    238       FileEnumerator::SHOW_SYM_LINKS);
    239   if (recursive)
    240     traverse_type = static_cast<FileEnumerator::FILE_TYPE>(
    241         traverse_type | FileEnumerator::DIRECTORIES);
    242   FileEnumerator traversal(from_path, recursive, traverse_type);
    243 
    244   // We have to mimic windows behavior here. |to_path| may not exist yet,
    245   // start the loop with |to_path|.
    246   FileEnumerator::FindInfo info;
    247   FilePath current = from_path;
    248   if (stat(from_path.value().c_str(), &info.stat) < 0) {
    249     LOG(ERROR) << "CopyDirectory() couldn't stat source directory: " <<
    250         from_path.value() << " errno = " << errno;
    251     success = false;
    252   }
    253   struct stat to_path_stat;
    254   FilePath from_path_base = from_path;
    255   if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
    256       S_ISDIR(to_path_stat.st_mode)) {
    257     // If the destination already exists and is a directory, then the
    258     // top level of source needs to be copied.
    259     from_path_base = from_path.DirName();
    260   }
    261 
    262   // The Windows version of this function assumes that non-recursive calls
    263   // will always have a directory for from_path.
    264   DCHECK(recursive || S_ISDIR(info.stat.st_mode));
    265 
    266   while (success && !current.empty()) {
    267     // current is the source path, including from_path, so paste
    268     // the suffix after from_path onto to_path to create the target_path.
    269     std::string suffix(&current.value().c_str()[from_path_base.value().size()]);
    270     // Strip the leading '/' (if any).
    271     if (!suffix.empty()) {
    272       DCHECK_EQ('/', suffix[0]);
    273       suffix.erase(0, 1);
    274     }
    275     const FilePath target_path = to_path.Append(suffix);
    276 
    277     if (S_ISDIR(info.stat.st_mode)) {
    278       if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 &&
    279           errno != EEXIST) {
    280         LOG(ERROR) << "CopyDirectory() couldn't create directory: " <<
    281             target_path.value() << " errno = " << errno;
    282         success = false;
    283       }
    284     } else if (S_ISREG(info.stat.st_mode)) {
    285       if (!CopyFile(current, target_path)) {
    286         LOG(ERROR) << "CopyDirectory() couldn't create file: " <<
    287             target_path.value();
    288         success = false;
    289       }
    290     } else {
    291       LOG(WARNING) << "CopyDirectory() skipping non-regular file: " <<
    292           current.value();
    293     }
    294 
    295     current = traversal.Next();
    296     traversal.GetFindInfo(&info);
    297   }
    298 
    299   return success;
    300 }
    301 
    302 bool PathExists(const FilePath& path) {
    303   stat_wrapper_t file_info;
    304   return CallStat(path.value().c_str(), &file_info) == 0;
    305 }
    306 
    307 bool PathIsWritable(const FilePath& path) {
    308   FilePath test_path(path);
    309   stat_wrapper_t file_info;
    310   if (CallStat(test_path.value().c_str(), &file_info) != 0)
    311     return false;
    312   if (S_IWOTH & file_info.st_mode)
    313     return true;
    314   if (getegid() == file_info.st_gid && (S_IWGRP & file_info.st_mode))
    315     return true;
    316   if (geteuid() == file_info.st_uid && (S_IWUSR & file_info.st_mode))
    317     return true;
    318   return false;
    319 }
    320 
    321 bool DirectoryExists(const FilePath& path) {
    322   stat_wrapper_t file_info;
    323   if (CallStat(path.value().c_str(), &file_info) == 0)
    324     return S_ISDIR(file_info.st_mode);
    325   return false;
    326 }
    327 
    328 // TODO(erikkay): implement
    329 #if 0
    330 bool GetFileCreationLocalTimeFromHandle(int fd,
    331                                         LPSYSTEMTIME creation_time) {
    332   if (!file_handle)
    333     return false;
    334 
    335   FILETIME utc_filetime;
    336   if (!GetFileTime(file_handle, &utc_filetime, NULL, NULL))
    337     return false;
    338 
    339   FILETIME local_filetime;
    340   if (!FileTimeToLocalFileTime(&utc_filetime, &local_filetime))
    341     return false;
    342 
    343   return !!FileTimeToSystemTime(&local_filetime, creation_time);
    344 }
    345 
    346 bool GetFileCreationLocalTime(const std::string& filename,
    347                               LPSYSTEMTIME creation_time) {
    348   ScopedHandle file_handle(
    349       CreateFile(filename.c_str(), GENERIC_READ,
    350                  FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
    351                  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
    352   return GetFileCreationLocalTimeFromHandle(file_handle.Get(), creation_time);
    353 }
    354 #endif
    355 
    356 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
    357   size_t total_read = 0;
    358   while (total_read < bytes) {
    359     ssize_t bytes_read =
    360         HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
    361     if (bytes_read <= 0)
    362       break;
    363     total_read += bytes_read;
    364   }
    365   return total_read == bytes;
    366 }
    367 
    368 // Creates and opens a temporary file in |directory|, returning the
    369 // file descriptor. |path| is set to the temporary file path.
    370 // This function does NOT unlink() the file.
    371 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
    372   *path = directory.Append(kTempFileName);
    373   const std::string& tmpdir_string = path->value();
    374   // this should be OK since mkstemp just replaces characters in place
    375   char* buffer = const_cast<char*>(tmpdir_string.c_str());
    376 
    377   return mkstemp(buffer);
    378 }
    379 
    380 bool CreateTemporaryFile(FilePath* path) {
    381   FilePath directory;
    382   if (!GetTempDir(&directory))
    383     return false;
    384   int fd = CreateAndOpenFdForTemporaryFile(directory, path);
    385   if (fd < 0)
    386     return false;
    387   close(fd);
    388   return true;
    389 }
    390 
    391 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path) {
    392   FilePath directory;
    393   if (!GetShmemTempDir(&directory))
    394     return false;
    395 
    396   return CreateAndOpenTemporaryFileInDir(directory, path);
    397 }
    398 
    399 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
    400   int fd = CreateAndOpenFdForTemporaryFile(dir, path);
    401   if (fd < 0)
    402     return NULL;
    403 
    404   return fdopen(fd, "a+");
    405 }
    406 
    407 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
    408   int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
    409   return ((fd >= 0) && !close(fd));
    410 }
    411 
    412 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
    413                             FilePath* new_temp_path) {
    414   FilePath tmpdir;
    415   if (!GetTempDir(&tmpdir))
    416     return false;
    417   tmpdir = tmpdir.Append(kTempFileName);
    418   std::string tmpdir_string = tmpdir.value();
    419   // this should be OK since mkdtemp just replaces characters in place
    420   char* buffer = const_cast<char*>(tmpdir_string.c_str());
    421   char* dtemp = mkdtemp(buffer);
    422   if (!dtemp)
    423     return false;
    424   *new_temp_path = FilePath(dtemp);
    425   return true;
    426 }
    427 
    428 bool CreateDirectory(const FilePath& full_path) {
    429   std::vector<FilePath> subpaths;
    430 
    431   // Collect a list of all parent directories.
    432   FilePath last_path = full_path;
    433   subpaths.push_back(full_path);
    434   for (FilePath path = full_path.DirName();
    435        path.value() != last_path.value(); path = path.DirName()) {
    436     subpaths.push_back(path);
    437     last_path = path;
    438   }
    439 
    440   // Iterate through the parents and create the missing ones.
    441   for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
    442        i != subpaths.rend(); ++i) {
    443     if (!DirectoryExists(*i)) {
    444       if (mkdir(i->value().c_str(), 0700) != 0)
    445         return false;
    446     }
    447   }
    448   return true;
    449 }
    450 
    451 bool GetFileInfo(const FilePath& file_path, FileInfo* results) {
    452   stat_wrapper_t file_info;
    453   if (CallStat(file_path.value().c_str(), &file_info) != 0)
    454     return false;
    455   results->is_directory = S_ISDIR(file_info.st_mode);
    456   results->size = file_info.st_size;
    457   results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
    458   return true;
    459 }
    460 
    461 bool GetInode(const FilePath& path, ino_t* inode) {
    462   struct stat buffer;
    463   int result = stat(path.value().c_str(), &buffer);
    464   if (result < 0)
    465     return false;
    466 
    467   *inode = buffer.st_ino;
    468   return true;
    469 }
    470 
    471 FILE* OpenFile(const std::string& filename, const char* mode) {
    472   return OpenFile(FilePath(filename), mode);
    473 }
    474 
    475 FILE* OpenFile(const FilePath& filename, const char* mode) {
    476   return fopen(filename.value().c_str(), mode);
    477 }
    478 
    479 int ReadFile(const FilePath& filename, char* data, int size) {
    480   int fd = open(filename.value().c_str(), O_RDONLY);
    481   if (fd < 0)
    482     return -1;
    483 
    484   ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
    485   if (int ret = HANDLE_EINTR(close(fd)) < 0)
    486     return ret;
    487   return bytes_read;
    488 }
    489 
    490 int WriteFile(const FilePath& filename, const char* data, int size) {
    491   int fd = creat(filename.value().c_str(), 0666);
    492   if (fd < 0)
    493     return -1;
    494 
    495   int bytes_written = WriteFileDescriptor(fd, data, size);
    496   if (int ret = HANDLE_EINTR(close(fd)) < 0)
    497     return ret;
    498   return bytes_written;
    499 }
    500 
    501 int WriteFileDescriptor(const int fd, const char* data, int size) {
    502   // Allow for partial writes.
    503   ssize_t bytes_written_total = 0;
    504   for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
    505        bytes_written_total += bytes_written_partial) {
    506     bytes_written_partial =
    507         HANDLE_EINTR(write(fd, data + bytes_written_total,
    508                            size - bytes_written_total));
    509     if (bytes_written_partial < 0)
    510       return -1;
    511   }
    512 
    513   return bytes_written_total;
    514 }
    515 
    516 // Gets the current working directory for the process.
    517 bool GetCurrentDirectory(FilePath* dir) {
    518   char system_buffer[PATH_MAX] = "";
    519   if (!getcwd(system_buffer, sizeof(system_buffer))) {
    520     NOTREACHED();
    521     return false;
    522   }
    523   *dir = FilePath(system_buffer);
    524   return true;
    525 }
    526 
    527 // Sets the current working directory for the process.
    528 bool SetCurrentDirectory(const FilePath& path) {
    529   int ret = chdir(path.value().c_str());
    530   return !ret;
    531 }
    532 
    533 ///////////////////////////////////////////////
    534 // FileEnumerator
    535 
    536 FileEnumerator::FileEnumerator(const FilePath& root_path,
    537                                bool recursive,
    538                                FileEnumerator::FILE_TYPE file_type)
    539     : current_directory_entry_(0),
    540       root_path_(root_path),
    541       recursive_(recursive),
    542       file_type_(file_type),
    543       is_in_find_op_(false) {
    544   // INCLUDE_DOT_DOT must not be specified if recursive.
    545   DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
    546   pending_paths_.push(root_path);
    547 }
    548 
    549 FileEnumerator::FileEnumerator(const FilePath& root_path,
    550                                bool recursive,
    551                                FileEnumerator::FILE_TYPE file_type,
    552                                const FilePath::StringType& pattern)
    553     : current_directory_entry_(0),
    554       root_path_(root_path),
    555       recursive_(recursive),
    556       file_type_(file_type),
    557       pattern_(root_path.Append(pattern).value()),
    558       is_in_find_op_(false) {
    559   // INCLUDE_DOT_DOT must not be specified if recursive.
    560   DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
    561   // The Windows version of this code appends the pattern to the root_path,
    562   // potentially only matching against items in the top-most directory.
    563   // Do the same here.
    564   if (pattern.size() == 0)
    565     pattern_ = FilePath::StringType();
    566   pending_paths_.push(root_path);
    567 }
    568 
    569 FileEnumerator::~FileEnumerator() {
    570 }
    571 
    572 void FileEnumerator::GetFindInfo(FindInfo* info) {
    573   DCHECK(info);
    574 
    575   if (current_directory_entry_ >= directory_entries_.size())
    576     return;
    577 
    578   DirectoryEntryInfo* cur_entry = &directory_entries_[current_directory_entry_];
    579   memcpy(&(info->stat), &(cur_entry->stat), sizeof(info->stat));
    580   info->filename.assign(cur_entry->filename.value());
    581 }
    582 
    583 bool FileEnumerator::IsDirectory(const FindInfo& info) {
    584   return S_ISDIR(info.stat.st_mode);
    585 }
    586 
    587 FilePath FileEnumerator::Next() {
    588   ++current_directory_entry_;
    589 
    590   // While we've exhausted the entries in the current directory, do the next
    591   while (current_directory_entry_ >= directory_entries_.size()) {
    592     if (pending_paths_.empty())
    593       return FilePath();
    594 
    595     root_path_ = pending_paths_.top();
    596     root_path_ = root_path_.StripTrailingSeparators();
    597     pending_paths_.pop();
    598 
    599     std::vector<DirectoryEntryInfo> entries;
    600     if (!ReadDirectory(&entries, root_path_, file_type_ & SHOW_SYM_LINKS))
    601       continue;
    602 
    603     directory_entries_.clear();
    604     current_directory_entry_ = 0;
    605     for (std::vector<DirectoryEntryInfo>::const_iterator
    606         i = entries.begin(); i != entries.end(); ++i) {
    607       FilePath full_path = root_path_.Append(i->filename);
    608       if (ShouldSkip(full_path))
    609         continue;
    610 
    611       if (pattern_.size() &&
    612           fnmatch(pattern_.c_str(), full_path.value().c_str(), FNM_NOESCAPE))
    613         continue;
    614 
    615       if (recursive_ && S_ISDIR(i->stat.st_mode))
    616         pending_paths_.push(full_path);
    617 
    618       if ((S_ISDIR(i->stat.st_mode) && (file_type_ & DIRECTORIES)) ||
    619           (!S_ISDIR(i->stat.st_mode) && (file_type_ & FILES)))
    620         directory_entries_.push_back(*i);
    621     }
    622   }
    623 
    624   return root_path_.Append(directory_entries_[current_directory_entry_
    625       ].filename);
    626 }
    627 
    628 bool FileEnumerator::ReadDirectory(std::vector<DirectoryEntryInfo>* entries,
    629                                    const FilePath& source, bool show_links) {
    630   DIR* dir = opendir(source.value().c_str());
    631   if (!dir)
    632     return false;
    633 
    634 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_FREEBSD) && \
    635     !defined(OS_OPENBSD)
    636   #error Port warning: depending on the definition of struct dirent, \
    637          additional space for pathname may be needed
    638 #endif
    639 
    640   struct dirent dent_buf;
    641   struct dirent* dent;
    642   while (readdir_r(dir, &dent_buf, &dent) == 0 && dent) {
    643     DirectoryEntryInfo info;
    644     info.filename = FilePath(dent->d_name);
    645 
    646     FilePath full_name = source.Append(dent->d_name);
    647     int ret;
    648     if (show_links)
    649       ret = lstat(full_name.value().c_str(), &info.stat);
    650     else
    651       ret = stat(full_name.value().c_str(), &info.stat);
    652     if (ret < 0) {
    653       // Print the stat() error message unless it was ENOENT and we're
    654       // following symlinks.
    655       if (!(ret == ENOENT && !show_links)) {
    656         PLOG(ERROR) << "Couldn't stat "
    657                     << source.Append(dent->d_name).value();
    658       }
    659       memset(&info.stat, 0, sizeof(info.stat));
    660     }
    661     entries->push_back(info);
    662   }
    663 
    664   closedir(dir);
    665   return true;
    666 }
    667 
    668 ///////////////////////////////////////////////
    669 // MemoryMappedFile
    670 
    671 MemoryMappedFile::MemoryMappedFile()
    672     : file_(base::kInvalidPlatformFileValue),
    673       data_(NULL),
    674       length_(0) {
    675 }
    676 
    677 bool MemoryMappedFile::MapFileToMemoryInternal() {
    678   struct stat file_stat;
    679   if (fstat(file_, &file_stat) == base::kInvalidPlatformFileValue) {
    680     LOG(ERROR) << "Couldn't fstat " << file_ << ", errno " << errno;
    681     return false;
    682   }
    683   length_ = file_stat.st_size;
    684 
    685   data_ = static_cast<uint8*>(
    686       mmap(NULL, length_, PROT_READ, MAP_SHARED, file_, 0));
    687   if (data_ == MAP_FAILED)
    688     LOG(ERROR) << "Couldn't mmap " << file_ << ", errno " << errno;
    689 
    690   return data_ != MAP_FAILED;
    691 }
    692 
    693 void MemoryMappedFile::CloseHandles() {
    694   if (data_ != NULL)
    695     munmap(data_, length_);
    696   if (file_ != base::kInvalidPlatformFileValue)
    697     close(file_);
    698 
    699   data_ = NULL;
    700   length_ = 0;
    701   file_ = base::kInvalidPlatformFileValue;
    702 }
    703 
    704 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo& find_info,
    705                               const base::Time& cutoff_time) {
    706   return find_info.stat.st_mtime >= cutoff_time.ToTimeT();
    707 }
    708 
    709 } // namespace file_util
    710