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 // A RandomAccessFile implementation backed by a file descriptor.
33 //
34 // Not thread safe.
35 class FdFile : public RandomAccessFile {
36  public:
37   static constexpr int kInvalidFd = -1;
38 
39   FdFile() = default;
40   // Creates an FdFile using the given file descriptor.
41   // Takes ownership of the file descriptor.
42   FdFile(int fd, bool check_usage);
43   FdFile(int fd, const std::string& path, bool check_usage);
44   FdFile(int fd, const std::string& path, bool check_usage, bool read_only_mode);
45 
FdFile(const std::string & path,int flags,bool check_usage)46   FdFile(const std::string& path, int flags, bool check_usage)
47       : FdFile(path, flags, 0640, check_usage) {}
48   FdFile(const std::string& path, int flags, mode_t mode, bool check_usage);
49 
50   // Move constructor.
51   FdFile(FdFile&& other) noexcept;
52 
53   // Move assignment operator.
54   FdFile& operator=(FdFile&& other) noexcept;
55 
56   // Release the file descriptor. This will make further accesses to this FdFile invalid. Disables
57   // all further state checking.
58   int Release();
59 
60   void Reset(int fd, bool check_usage);
61 
62   // Destroys an FdFile, closing the file descriptor if Close hasn't already
63   // been called. (If you care about the return value of Close, call it
64   // yourself; this is meant to handle failure cases and read-only accesses.
65   // Note though that calling Close and checking its return value is still no
66   // guarantee that data actually made it to stable storage.)
67   virtual ~FdFile();
68 
69   // RandomAccessFile API.
70   int Close() override WARN_UNUSED;
71   int64_t Read(char* buf, int64_t byte_count, int64_t offset) const override WARN_UNUSED;
72   int SetLength(int64_t new_length) override WARN_UNUSED;
73   int64_t GetLength() const override;
74   int64_t Write(const char* buf, int64_t byte_count, int64_t offset) override WARN_UNUSED;
75 
76   int Flush() override WARN_UNUSED;
77 
78   // Short for SetLength(0); Flush(); Close();
79   // If the file was opened with a path name and unlink = true, also calls Unlink() on the path.
80   // Note that it is the the caller's responsibility to avoid races.
81   bool Erase(bool unlink = false);
82 
83   // Call unlink() if the file was opened with a path, and if open() with the name shows that
84   // the file descriptor of this file is still up-to-date. This is still racy, though, and it
85   // is up to the caller to ensure correctness in a multi-process setup.
86   bool Unlink();
87 
88   // Try to Flush(), then try to Close(); If either fails, call Erase().
89   int FlushCloseOrErase() WARN_UNUSED;
90 
91   // Try to Flush and Close(). Attempts both, but returns the first error.
92   int FlushClose() WARN_UNUSED;
93 
94   // Bonus API.
95   int Fd() const;
96   bool ReadOnlyMode() const;
97   bool CheckUsage() const;
98 
99   // Check whether the underlying file descriptor refers to an open file.
100   bool IsOpened() const;
101 
102   // Check whether the numeric value of the underlying file descriptor is valid (Fd() != -1).
IsValid()103   bool IsValid() const { return fd_ != kInvalidFd; }
104 
GetPath()105   const std::string& GetPath() const {
106     return file_path_;
107   }
108   bool ReadFully(void* buffer, size_t byte_count) WARN_UNUSED;
109   bool PreadFully(void* buffer, size_t byte_count, size_t offset) WARN_UNUSED;
110   bool WriteFully(const void* buffer, size_t byte_count) WARN_UNUSED;
111   bool PwriteFully(const void* buffer, size_t byte_count, size_t offset) WARN_UNUSED;
112 
113   // Copy data from another file.
114   bool Copy(FdFile* input_file, int64_t offset, int64_t size);
115   // Clears the file content and resets the file offset to 0.
116   // Returns true upon success, false otherwise.
117   bool ClearContent();
118   // Resets the file offset to the beginning of the file.
119   bool ResetOffset();
120 
121   // This enum is public so that we can define the << operator over it.
122   enum class GuardState {
123     kBase,           // Base, file has not been flushed or closed.
124     kFlushed,        // File has been flushed, but not closed.
125     kClosed,         // File has been flushed and closed.
126     kNoCheck         // Do not check for the current file instance.
127   };
128 
129   // WARNING: Only use this when you know what you're doing!
130   void MarkUnchecked();
131 
132   // Compare against another file. Returns 0 if the files are equivalent, otherwise returns -1 or 1
133   // depending on if the lengths are different. If the lengths are the same, the function returns
134   // the difference of the first byte that differs.
135   int Compare(FdFile* other);
136 
137   // Check that `fd` has a valid value (!= kInvalidFd) and refers to an open file.
138   // On Windows, this call only checks that the value of `fd` is valid .
139   static bool IsOpenFd(int fd);
140 
141  protected:
142   // If the guard state indicates checking (!=kNoCheck), go to the target state `target`. Print the
143   // given warning if the current state is or exceeds warn_threshold.
144   void moveTo(GuardState target, GuardState warn_threshold, const char* warning);
145 
146   // If the guard state indicates checking (<kNoCheck), and is below the target state `target`, go
147   // to `target`. If the current state is higher (excluding kNoCheck) than the target state, print
148   // the warning.
149   void moveUp(GuardState target, const char* warning);
150 
151   // Forcefully sets the state to the given one. This can overwrite kNoCheck.
resetGuard(GuardState new_state)152   void resetGuard(GuardState new_state) {
153     if (kCheckSafeUsage) {
154       guard_state_ = new_state;
155     }
156   }
157 
158   GuardState guard_state_ = GuardState::kClosed;
159 
160   // Opens file `file_path` using `flags` and `mode`.
161   bool Open(const std::string& file_path, int flags);
162   bool Open(const std::string& file_path, int flags, mode_t mode);
163 
164  private:
165   template <bool kUseOffset>
166   bool WriteFullyGeneric(const void* buffer, size_t byte_count, size_t offset);
167 
168   void Destroy();  // For ~FdFile and operator=(&&).
169 
170   int fd_ = kInvalidFd;
171   std::string file_path_;
172   bool read_only_mode_ = false;
173 
174   DISALLOW_COPY_AND_ASSIGN(FdFile);
175 };
176 
177 std::ostream& operator<<(std::ostream& os, FdFile::GuardState kind);
178 
179 }  // namespace unix_file
180 
181 #endif  // ART_LIBARTBASE_BASE_UNIX_FILE_FD_FILE_H_
182