github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/util/fs_util.h (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  #ifndef GVISOR_TEST_UTIL_FS_UTIL_H_
    16  #define GVISOR_TEST_UTIL_FS_UTIL_H_
    17  
    18  #include <dirent.h>
    19  #include <sys/stat.h>
    20  #include <sys/statfs.h>
    21  #include <sys/types.h>
    22  #include <unistd.h>
    23  
    24  #include "absl/strings/string_view.h"
    25  #include "test/util/file_descriptor.h"
    26  #include "test/util/posix_error.h"
    27  
    28  namespace gvisor {
    29  namespace testing {
    30  
    31  // O_LARGEFILE as defined by Linux. glibc tries to be clever by setting it to 0
    32  // because "it isn't needed", even though Linux can return it via F_GETFL.
    33  #if defined(__x86_64__)
    34  constexpr int kOLargeFile = 00100000;
    35  #elif defined(__aarch64__)
    36  constexpr int kOLargeFile = 00400000;
    37  #else
    38  #error "Unknown architecture"
    39  #endif
    40  
    41  // From linux/magic.h. For some reason, not defined in the headers for some
    42  // build environments.
    43  #define OVERLAYFS_SUPER_MAGIC 0x794c7630
    44  
    45  // Returns a status or the current working directory.
    46  PosixErrorOr<std::string> GetCWD();
    47  
    48  // Returns true/false depending on whether or not path exists, or an error if it
    49  // can't be determined.
    50  PosixErrorOr<bool> Exists(absl::string_view path);
    51  
    52  // Returns a stat structure for the given path or an error. If the path
    53  // represents a symlink, it will be traversed.
    54  PosixErrorOr<struct stat> Stat(absl::string_view path);
    55  
    56  // Returns a stat structure for the given path or an error. If the path
    57  // represents a symlink, it will not be traversed.
    58  PosixErrorOr<struct stat> Lstat(absl::string_view path);
    59  
    60  // Returns a stat struct for the given fd.
    61  PosixErrorOr<struct stat> Fstat(int fd);
    62  
    63  // Deletes the file or directory at path or returns an error.
    64  PosixError Delete(absl::string_view path);
    65  
    66  // Changes the mode of a file or returns an error.
    67  PosixError Chmod(absl::string_view path, int mode);
    68  
    69  // Create a special or ordinary file.
    70  PosixError MknodAt(const FileDescriptor& dfd, absl::string_view path, int mode,
    71                     dev_t dev);
    72  
    73  // Unlink the file.
    74  PosixError UnlinkAt(const FileDescriptor& dfd, absl::string_view path,
    75                      int flags);
    76  
    77  // Truncates a file to the given length or returns an error.
    78  PosixError Truncate(absl::string_view path, int length);
    79  
    80  // Returns true/false depending on whether or not the path is a directory or
    81  // returns an error.
    82  PosixErrorOr<bool> IsDirectory(absl::string_view path);
    83  
    84  // Makes a directory or returns an error.
    85  PosixError Mkdir(absl::string_view path, int mode = 0755);
    86  
    87  // Removes a directory or returns an error.
    88  PosixError Rmdir(absl::string_view path);
    89  
    90  // Attempts to set the contents of a file or returns an error.
    91  PosixError SetContents(absl::string_view path, absl::string_view contents);
    92  
    93  // Creates a file with the given contents and mode or returns an error.
    94  PosixError CreateWithContents(absl::string_view path,
    95                                absl::string_view contents, int mode = 0666);
    96  
    97  // Attempts to read the entire contents of the file into the provided string
    98  // buffer or returns an error.
    99  PosixError GetContents(absl::string_view path, std::string* output);
   100  
   101  // Attempts to read the entire contents of the file or returns an error.
   102  PosixErrorOr<std::string> GetContents(absl::string_view path);
   103  
   104  // Attempts to read the entire contents of the provided fd into the provided
   105  // string or returns an error.
   106  PosixError GetContentsFD(int fd, std::string* output);
   107  
   108  // Attempts to read the entire contents of the provided fd or returns an error.
   109  PosixErrorOr<std::string> GetContentsFD(int fd);
   110  
   111  // Executes the readlink(2) system call or returns an error.
   112  PosixErrorOr<std::string> ReadLink(absl::string_view path);
   113  
   114  // WalkTree will walk a directory tree in a depth first search manner (if
   115  // recursive). It will invoke a provided callback for each file and directory,
   116  // the parent will always be invoked last making this appropriate for things
   117  // such as deleting an entire directory tree.
   118  //
   119  // This method will return an error when it's unable to access the provided
   120  // path, or when the path is not a directory.
   121  PosixError WalkTree(
   122      absl::string_view path, bool recursive,
   123      const std::function<void(absl::string_view, const struct stat&)>& cb);
   124  
   125  // Returns the base filenames for all files under a given absolute path. If
   126  // skipdots is true the returned vector will not contain "." or "..". This
   127  // method does not walk the tree recursively it only returns the elements
   128  // in that directory.
   129  PosixErrorOr<std::vector<std::string>> ListDir(absl::string_view abspath,
   130                                                 bool skipdots);
   131  
   132  // Check that a directory contains children nodes named in expect, and does not
   133  // contain any children nodes named in exclude.
   134  PosixError DirContains(absl::string_view path,
   135                         const std::vector<std::string>& expect,
   136                         const std::vector<std::string>& exclude);
   137  
   138  // Same as DirContains, but adds a retry. Suitable for checking a directory
   139  // being modified asynchronously.
   140  PosixError EventuallyDirContains(absl::string_view path,
   141                                   const std::vector<std::string>& expect,
   142                                   const std::vector<std::string>& exclude);
   143  
   144  // Attempt to recursively delete a directory or file. Returns an error and
   145  // the number of undeleted directories and files. If either
   146  // undeleted_dirs or undeleted_files is nullptr then it will not be used.
   147  PosixError RecursivelyDelete(absl::string_view path, int* undeleted_dirs,
   148                               int* undeleted_files);
   149  
   150  // Recursively create the directory provided or return an error.
   151  PosixError RecursivelyCreateDir(absl::string_view path);
   152  
   153  // Makes a path absolute with respect to an optional base. If no base is
   154  // provided it will use the current working directory.
   155  PosixErrorOr<std::string> MakeAbsolute(absl::string_view filename,
   156                                         absl::string_view base);
   157  
   158  // Generates a relative path from the source directory to the destination
   159  // (dest) file or directory.  This uses ../ when necessary for destinations
   160  // which are not nested within the source.  Both source and dest are required
   161  // to be absolute paths, and an empty string will be returned if they are not.
   162  PosixErrorOr<std::string> GetRelativePath(absl::string_view source,
   163                                            absl::string_view dest);
   164  
   165  // Returns the part of the path before the final "/", EXCEPT:
   166  // * If there is a single leading "/" in the path, the result will be the
   167  //   leading "/".
   168  // * If there is no "/" in the path, the result is the empty prefix of the
   169  //   input string.
   170  absl::string_view Dirname(absl::string_view path);
   171  
   172  // Return the parts of the path, split on the final "/".  If there is no
   173  // "/" in the path, the first part of the output is empty and the second
   174  // is the input. If the only "/" in the path is the first character, it is
   175  // the first part of the output.
   176  std::pair<absl::string_view, absl::string_view> SplitPath(
   177      absl::string_view path);
   178  
   179  // Returns the part of the path after the final "/". If there is no
   180  // "/" in the path, the result is the same as the input.
   181  // Note that this function's behavior differs from the Unix basename
   182  // command if path ends with "/". For such paths, this function returns the
   183  // empty string.
   184  absl::string_view Basename(absl::string_view path);
   185  
   186  // Collapse duplicate "/"s, resolve ".." and "." path elements, remove
   187  // trailing "/".
   188  //
   189  // NOTE: This respects relative vs. absolute paths, but does not
   190  // invoke any system calls (getcwd(2)) in order to resolve relative
   191  // paths wrt actual working directory.  That is, this is purely a
   192  // string manipulation, completely independent of process state.
   193  std::string CleanPath(absl::string_view path);
   194  
   195  // Returns the full path to the executable of the given pid or a PosixError.
   196  PosixErrorOr<std::string> ProcessExePath(int pid);
   197  
   198  #ifdef __linux__
   199  // IsTmpfs returns true if the file at path is backed by tmpfs.
   200  PosixErrorOr<bool> IsTmpfs(const std::string& path);
   201  #endif  // __linux__
   202  
   203  // IsOverlayfs returns true if the file at path is backed by overlayfs.
   204  PosixErrorOr<bool> IsOverlayfs(const std::string& path);
   205  
   206  PosixError CheckSameFile(const FileDescriptor& fd1, const FileDescriptor& fd2);
   207  
   208  namespace internal {
   209  // Not part of the public API.
   210  std::string JoinPathImpl(std::initializer_list<absl::string_view> paths);
   211  }  // namespace internal
   212  
   213  // Join multiple paths together.
   214  // All paths will be treated as relative paths, regardless of whether or not
   215  // they start with a leading '/'.  That is, all paths will be concatenated
   216  // together, with the appropriate path separator inserted in between.
   217  // Arguments must be convertible to absl::string_view.
   218  //
   219  // Usage:
   220  // std::string path = JoinPath("/foo", dirname, filename);
   221  // std::string path = JoinPath(FLAGS_test_srcdir, filename);
   222  //
   223  // 0, 1, 2-path specializations exist to optimize common cases.
   224  inline std::string JoinPath() { return std::string(); }
   225  inline std::string JoinPath(absl::string_view path) {
   226    return std::string(path.data(), path.size());
   227  }
   228  
   229  std::string JoinPath(absl::string_view path1, absl::string_view path2);
   230  template <typename... T>
   231  inline std::string JoinPath(absl::string_view path1, absl::string_view path2,
   232                              absl::string_view path3, const T&... args) {
   233    return internal::JoinPathImpl({path1, path2, path3, args...});
   234  }
   235  }  // namespace testing
   236  }  // namespace gvisor
   237  #endif  // GVISOR_TEST_UTIL_FS_UTIL_H_