• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_LIBARTBASE_BASE_UNIX_FILE_FD_FILE_H_
18 #define ART_LIBARTBASE_BASE_UNIX_FILE_FD_FILE_H_
19 
20 #include <fcntl.h>
21 
22 #include <string>
23 
24 #include "base/macros.h"
25 #include "random_access_file.h"
26 
27 namespace unix_file {
28 
29 // If true, check whether Flush and Close are called before destruction.
30 static constexpr bool kCheckSafeUsage = true;
31 
32 // Used to work around kernel bugs.
33 bool AllowSparseFiles();
34 
35 // A RandomAccessFile implementation backed by a file descriptor.
36 //
37 // Not thread safe.
38 class FdFile : public RandomAccessFile {
39  public:
40   static constexpr int kInvalidFd = -1;
41 
42   FdFile() = default;
43   // Creates an FdFile using the given file descriptor.
44   // Takes ownership of the file descriptor.
45   FdFile(int fd, bool check_usage);
46   FdFile(int fd, const std::string& path, bool check_usage);
47   FdFile(int fd, const std::string& path, bool check_usage, bool read_only_mode);
48 
FdFile(const std::string & path,int flags,bool check_usage)49   FdFile(const std::string& path, int flags, bool check_usage)
50       : FdFile(path, flags, 0640, check_usage) {}
51   FdFile(const std::string& path, int flags, mode_t mode, bool check_usage);
52 
53   // Move constructor.
54   FdFile(FdFile&& other) noexcept;
55 
56   // Move assignment operator.
57   FdFile& operator=(FdFile&& other) noexcept;
58 
59   // Release the file descriptor. This will make further accesses to this FdFile invalid. Disables
60   // all further state checking.
61   int Release();
62 
63   void Reset(int fd, bool check_usage);
64 
65   // Destroys an FdFile, closing the file descriptor if Close hasn't already
66   // been called. (If you care about the return value of Close, call it
67   // yourself; this is meant to handle failure cases and read-only accesses.
68   // Note though that calling Close and checking its return value is still no
69   // guarantee that data actually made it to stable storage.)
70   virtual ~FdFile();
71 
72   // RandomAccessFile API.
73   int Close() override WARN_UNUSED;
74   int64_t Read(char* buf, int64_t byte_count, int64_t offset) const override WARN_UNUSED;
75   int SetLength(int64_t new_length) override WARN_UNUSED;
76   int64_t GetLength() const override;
77   int64_t Write(const char* buf, int64_t byte_count, int64_t offset) override WARN_UNUSED;
78 
Flush()79   int Flush() override WARN_UNUSED { return Flush(/*flush_metadata=*/false); }
80   int Flush(bool flush_metadata) WARN_UNUSED;
81 
82   // Short for SetLength(0); Flush(); Close();
83   // If the file was opened with a path name and unlink = true, also calls Unlink() on the path.
84   // Note that it is the the caller's responsibility to avoid races.
85   bool Erase(bool unlink = false);
86 
87   // Call unlink(), though only if FilePathMatchesFd() returns true.
88   bool Unlink();
89 
90   // Try to Flush(), then try to Close(); If either fails, call Erase().
91   int FlushCloseOrErase() WARN_UNUSED;
92 
93   // Try to Flush and Close(). Attempts both, but returns the first error.
94   int FlushClose() WARN_UNUSED;
95 
96   // Bonus API.
97   int Fd() const;
98   bool ReadOnlyMode() const;
99   bool CheckUsage() const;
100 
101   // Check whether the underlying file descriptor refers to an open file.
102   bool IsOpened() const;
103 
104   // Check whether the numeric value of the underlying file descriptor is valid (Fd() != -1).
IsValid()105   bool IsValid() const { return fd_ != kInvalidFd; }
106 
GetPath()107   const std::string& GetPath() const {
108     return file_path_;
109   }
110   bool ReadFully(void* buffer, size_t byte_count) WARN_UNUSED;
111   bool PreadFully(void* buffer, size_t byte_count, size_t offset) WARN_UNUSED;
112   bool WriteFully(const void* buffer, size_t byte_count) WARN_UNUSED;
113   bool PwriteFully(const void* buffer, size_t byte_count, size_t offset) WARN_UNUSED;
114 
115   // Change the file path, though only if FilePathMatchesFd() returns true.
116   //
117   // If a file at new_path already exists, it will be replaced.
118   // On Linux, the rename syscall will fail unless the source and destination are on the same
119   // mounted filesystem.
120   // This function is not expected to modify the file data itself, instead it modifies the inodes of
121   // the source and destination directories, and therefore the function flushes those file
122   // descriptors following the rename.
123   bool Rename(const std::string& new_path);
124   // Copy data from another file.
125   // On Linux, we only support copies that will append regions to the file, and we require the file
126   // offset of the output file descriptor to be aligned with the filesystem blocksize (see comments
127   // in implementation).
128   bool Copy(FdFile* input_file, int64_t offset, int64_t size);
129   // Clears the file content and resets the file offset to 0.
130   // Returns true upon success, false otherwise.
131   bool ClearContent();
132   // Resets the file offset to the beginning of the file.
133   bool ResetOffset();
134 
135   // This enum is public so that we can define the << operator over it.
136   enum class GuardState {
137     kBase,           // Base, file has not been flushed or closed.
138     kFlushed,        // File has been flushed, but not closed.
139     kClosed,         // File has been flushed and closed.
140     kNoCheck         // Do not check for the current file instance.
141   };
142 
143   // WARNING: Only use this when you know what you're doing!
144   void MarkUnchecked();
145 
146   // Compare against another file. Returns 0 if the files are equivalent, otherwise returns -1 or 1
147   // depending on if the lengths are different. If the lengths are the same, the function returns
148   // the difference of the first byte that differs.
149   int Compare(FdFile* other);
150 
151   // Check that `fd` has a valid value (!= kInvalidFd) and refers to an open file.
152   // On Windows, this call only checks that the value of `fd` is valid .
153   static bool IsOpenFd(int fd);
154 
155  protected:
156   // If the guard state indicates checking (!=kNoCheck), go to the target state `target`. Print the
157   // given warning if the current state is or exceeds warn_threshold.
158   void moveTo(GuardState target, GuardState warn_threshold, const char* warning);
159 
160   // If the guard state indicates checking (<kNoCheck), and is below the target state `target`, go
161   // to `target`. If the current state is higher (excluding kNoCheck) than the target state, print
162   // the warning.
163   void moveUp(GuardState target, const char* warning);
164 
165   // Forcefully sets the state to the given one. This can overwrite kNoCheck.
resetGuard(GuardState new_state)166   void resetGuard(GuardState new_state) {
167     if (kCheckSafeUsage) {
168       guard_state_ = new_state;
169     }
170   }
171 
172   GuardState guard_state_ = GuardState::kClosed;
173 
174   // Opens file `file_path` using `flags` and `mode`.
175   bool Open(const std::string& file_path, int flags);
176   bool Open(const std::string& file_path, int flags, mode_t mode);
177 
178  private:
179   template <bool kUseOffset>
180   bool WriteFullyGeneric(const void* buffer, size_t byte_count, size_t offset);
181 
182   // The file path we hold for the file descriptor may be invalid, or may not even exist (e.g. if
183   // the FdFile wasn't initialised with a path). This helper function checks if calling open() on
184   // the file path (if it is set) returns the expected up-to-date file descriptor. This is still
185   // racy, though, and it is up to the caller to ensure correctness in a multi-process setup.
186   bool FilePathMatchesFd();
187 
188 #ifdef __linux__
189   // Sparse copy of 'size' bytes from an input file, starting at 'off'. Both this file's offset and
190   // the input file's offset will be incremented by 'size' bytes.
191   //
192   // Note: in order to preserve the same sparsity, the input and output files must be on mounted
193   // filesystems that use the same blocksize, and the offsets used for the copy must be aligned to
194   // it. Otherwise, the copied region's sparsity within the output file may differ from its original
195   // sparsity in the input file.
196   bool UserspaceSparseCopy(const FdFile* input_file, off_t off, size_t size, size_t fs_blocksize);
197 
198   // Write 'size' bytes from 'data' to the file if any are non-zero. Otherwise, just update the file
199   // offset and skip the write. For efficiency, the function expects a vector of zeroed uint8_t
200   // values to check the data array against. This vector 'zeroes' must have length greater than or
201   // equal to 'size'.
202   //
203   // As filesystems which support sparse files only allocate physical space to blocks that have been
204   // written, any whole filesystem blocks in the output file which are skipped in this way will save
205   // storage space. Subsequent reads of bytes in non-allocated blocks will simply return zeros
206   // without accessing the underlying storage.
207   bool SparseWrite(const uint8_t* data,
208                    size_t size,
209                    const std::vector<uint8_t>& zeroes);
210 #endif
211 
212   void Destroy();  // For ~FdFile and operator=(&&).
213 
214   int fd_ = kInvalidFd;
215   std::string file_path_;
216   bool read_only_mode_ = false;
217 
218   DISALLOW_COPY_AND_ASSIGN(FdFile);
219 };
220 
221 std::ostream& operator<<(std::ostream& os, FdFile::GuardState kind);
222 
223 }  // namespace unix_file
224 
225 #endif  // ART_LIBARTBASE_BASE_UNIX_FILE_FD_FILE_H_
226