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