File.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. //===-- File.h --------------------------------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef LLDB_HOST_FILE_H
  9. #define LLDB_HOST_FILE_H
  10. #include "lldb/Host/PosixApi.h"
  11. #include "lldb/Utility/IOObject.h"
  12. #include "lldb/Utility/Status.h"
  13. #include "lldb/lldb-private.h"
  14. #include "llvm/ADT/BitmaskEnum.h"
  15. #include <cstdarg>
  16. #include <cstdio>
  17. #include <mutex>
  18. #include <sys/types.h>
  19. namespace lldb_private {
  20. LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
  21. /// \class File File.h "lldb/Host/File.h"
  22. /// An abstract base class for files.
  23. ///
  24. /// Files will often be NativeFiles, which provides a wrapper
  25. /// around host OS file functionality. But it
  26. /// is also possible to subclass file to provide objects that have file
  27. /// or stream functionality but are not backed by any host OS file.
  28. class File : public IOObject {
  29. public:
  30. static int kInvalidDescriptor;
  31. static FILE *kInvalidStream;
  32. // NB this enum is used in the lldb platform gdb-remote packet
  33. // vFile:open: and existing values cannot be modified.
  34. //
  35. // FIXME
  36. // These values do not match the values used by GDB
  37. // * https://sourceware.org/gdb/onlinedocs/gdb/Open-Flags.html#Open-Flags
  38. // * rdar://problem/46788934
  39. enum OpenOptions : uint32_t {
  40. eOpenOptionRead = (1u << 0), // Open file for reading
  41. eOpenOptionWrite = (1u << 1), // Open file for writing
  42. eOpenOptionAppend =
  43. (1u << 2), // Don't truncate file when opening, append to end of file
  44. eOpenOptionTruncate = (1u << 3), // Truncate file when opening
  45. eOpenOptionNonBlocking = (1u << 4), // File reads
  46. eOpenOptionCanCreate = (1u << 5), // Create file if doesn't already exist
  47. eOpenOptionCanCreateNewOnly =
  48. (1u << 6), // Can create file only if it doesn't already exist
  49. eOpenOptionDontFollowSymlinks = (1u << 7),
  50. eOpenOptionCloseOnExec =
  51. (1u << 8), // Close the file when executing a new process
  52. LLVM_MARK_AS_BITMASK_ENUM(/* largest_value= */ eOpenOptionCloseOnExec)
  53. };
  54. static mode_t ConvertOpenOptionsForPOSIXOpen(OpenOptions open_options);
  55. static llvm::Expected<OpenOptions> GetOptionsFromMode(llvm::StringRef mode);
  56. static bool DescriptorIsValid(int descriptor) { return descriptor >= 0; };
  57. static llvm::Expected<const char *>
  58. GetStreamOpenModeFromOptions(OpenOptions options);
  59. File()
  60. : IOObject(eFDTypeFile), m_is_interactive(eLazyBoolCalculate),
  61. m_is_real_terminal(eLazyBoolCalculate),
  62. m_supports_colors(eLazyBoolCalculate){};
  63. /// Read bytes from a file from the current file position into buf.
  64. ///
  65. /// NOTE: This function is NOT thread safe. Use the read function
  66. /// that takes an "off_t &offset" to ensure correct operation in multi-
  67. /// threaded environments.
  68. ///
  69. /// \param[in,out] num_bytes
  70. /// Pass in the size of buf. Read will pass out the number
  71. /// of bytes read. Zero bytes read with no error indicates
  72. /// EOF.
  73. ///
  74. /// \return
  75. /// success, ENOTSUP, or another error.
  76. Status Read(void *buf, size_t &num_bytes) override;
  77. /// Write bytes from buf to a file at the current file position.
  78. ///
  79. /// NOTE: This function is NOT thread safe. Use the write function
  80. /// that takes an "off_t &offset" to ensure correct operation in multi-
  81. /// threaded environments.
  82. ///
  83. /// \param[in,out] num_bytes
  84. /// Pass in the size of buf. Write will pass out the number
  85. /// of bytes written. Write will attempt write the full number
  86. /// of bytes and will not return early except on error.
  87. ///
  88. /// \return
  89. /// success, ENOTSUP, or another error.
  90. Status Write(const void *buf, size_t &num_bytes) override;
  91. /// IsValid
  92. ///
  93. /// \return
  94. /// true iff the file is valid.
  95. bool IsValid() const override;
  96. /// Flush any buffers and release any resources owned by the file.
  97. /// After Close() the file will be invalid.
  98. ///
  99. /// \return
  100. /// success or an error.
  101. Status Close() override;
  102. /// Get a handle that can be used for OS polling interfaces, such
  103. /// as WaitForMultipleObjects, select, or epoll. This may return
  104. /// IOObject::kInvalidHandleValue if none is available. This will
  105. /// generally be the same as the file descriptor, this function
  106. /// is not interchangeable with GetDescriptor(). A WaitableHandle
  107. /// must only be used for polling, not actual I/O.
  108. ///
  109. /// \return
  110. /// a valid handle or IOObject::kInvalidHandleValue
  111. WaitableHandle GetWaitableHandle() override;
  112. /// Get the file specification for this file, if possible.
  113. ///
  114. /// \param[out] file_spec
  115. /// the file specification.
  116. /// \return
  117. /// ENOTSUP, success, or another error.
  118. virtual Status GetFileSpec(FileSpec &file_spec) const;
  119. /// Get underlying OS file descriptor for this file, or kInvalidDescriptor.
  120. /// If the descriptor is valid, then it may be used directly for I/O
  121. /// However, the File may also perform it's own buffering, so avoid using
  122. /// this if it is not necessary, or use Flush() appropriately.
  123. ///
  124. /// \return
  125. /// a valid file descriptor for this file or kInvalidDescriptor
  126. virtual int GetDescriptor() const;
  127. /// Get the underlying libc stream for this file, or NULL.
  128. ///
  129. /// Not all valid files will have a FILE* stream. This should only be
  130. /// used if absolutely necessary, such as to interact with 3rd party
  131. /// libraries that need FILE* streams.
  132. ///
  133. /// \return
  134. /// a valid stream or NULL;
  135. virtual FILE *GetStream();
  136. /// Seek to an offset relative to the beginning of the file.
  137. ///
  138. /// NOTE: This function is NOT thread safe, other threads that
  139. /// access this object might also change the current file position. For
  140. /// thread safe reads and writes see the following functions: @see
  141. /// File::Read (void *, size_t, off_t &) \see File::Write (const void *,
  142. /// size_t, off_t &)
  143. ///
  144. /// \param[in] offset
  145. /// The offset to seek to within the file relative to the
  146. /// beginning of the file.
  147. ///
  148. /// \param[in] error_ptr
  149. /// A pointer to a lldb_private::Status object that will be
  150. /// filled in if non-nullptr.
  151. ///
  152. /// \return
  153. /// The resulting seek offset, or -1 on error.
  154. virtual off_t SeekFromStart(off_t offset, Status *error_ptr = nullptr);
  155. /// Seek to an offset relative to the current file position.
  156. ///
  157. /// NOTE: This function is NOT thread safe, other threads that
  158. /// access this object might also change the current file position. For
  159. /// thread safe reads and writes see the following functions: @see
  160. /// File::Read (void *, size_t, off_t &) \see File::Write (const void *,
  161. /// size_t, off_t &)
  162. ///
  163. /// \param[in] offset
  164. /// The offset to seek to within the file relative to the
  165. /// current file position.
  166. ///
  167. /// \param[in] error_ptr
  168. /// A pointer to a lldb_private::Status object that will be
  169. /// filled in if non-nullptr.
  170. ///
  171. /// \return
  172. /// The resulting seek offset, or -1 on error.
  173. virtual off_t SeekFromCurrent(off_t offset, Status *error_ptr = nullptr);
  174. /// Seek to an offset relative to the end of the file.
  175. ///
  176. /// NOTE: This function is NOT thread safe, other threads that
  177. /// access this object might also change the current file position. For
  178. /// thread safe reads and writes see the following functions: @see
  179. /// File::Read (void *, size_t, off_t &) \see File::Write (const void *,
  180. /// size_t, off_t &)
  181. ///
  182. /// \param[in,out] offset
  183. /// The offset to seek to within the file relative to the
  184. /// end of the file which gets filled in with the resulting
  185. /// absolute file offset.
  186. ///
  187. /// \param[in] error_ptr
  188. /// A pointer to a lldb_private::Status object that will be
  189. /// filled in if non-nullptr.
  190. ///
  191. /// \return
  192. /// The resulting seek offset, or -1 on error.
  193. virtual off_t SeekFromEnd(off_t offset, Status *error_ptr = nullptr);
  194. /// Read bytes from a file from the specified file offset.
  195. ///
  196. /// NOTE: This function is thread safe in that clients manager their
  197. /// own file position markers and reads on other threads won't mess up the
  198. /// current read.
  199. ///
  200. /// \param[in] dst
  201. /// A buffer where to put the bytes that are read.
  202. ///
  203. /// \param[in,out] num_bytes
  204. /// The number of bytes to read form the current file position
  205. /// which gets modified with the number of bytes that were read.
  206. ///
  207. /// \param[in,out] offset
  208. /// The offset within the file from which to read \a num_bytes
  209. /// bytes. This offset gets incremented by the number of bytes
  210. /// that were read.
  211. ///
  212. /// \return
  213. /// An error object that indicates success or the reason for
  214. /// failure.
  215. virtual Status Read(void *dst, size_t &num_bytes, off_t &offset);
  216. /// Write bytes to a file at the specified file offset.
  217. ///
  218. /// NOTE: This function is thread safe in that clients manager their
  219. /// own file position markers, though clients will need to implement their
  220. /// own locking externally to avoid multiple people writing to the file at
  221. /// the same time.
  222. ///
  223. /// \param[in] src
  224. /// A buffer containing the bytes to write.
  225. ///
  226. /// \param[in,out] num_bytes
  227. /// The number of bytes to write to the file at offset \a offset.
  228. /// \a num_bytes gets modified with the number of bytes that
  229. /// were read.
  230. ///
  231. /// \param[in,out] offset
  232. /// The offset within the file at which to write \a num_bytes
  233. /// bytes. This offset gets incremented by the number of bytes
  234. /// that were written.
  235. ///
  236. /// \return
  237. /// An error object that indicates success or the reason for
  238. /// failure.
  239. virtual Status Write(const void *src, size_t &num_bytes, off_t &offset);
  240. /// Flush the current stream
  241. ///
  242. /// \return
  243. /// An error object that indicates success or the reason for
  244. /// failure.
  245. virtual Status Flush();
  246. /// Sync to disk.
  247. ///
  248. /// \return
  249. /// An error object that indicates success or the reason for
  250. /// failure.
  251. virtual Status Sync();
  252. /// Output printf formatted output to the stream.
  253. ///
  254. /// NOTE: this is not virtual, because it just calls the va_list
  255. /// version of the function.
  256. ///
  257. /// Print some formatted output to the stream.
  258. ///
  259. /// \param[in] format
  260. /// A printf style format string.
  261. ///
  262. /// \param[in] ...
  263. /// Variable arguments that are needed for the printf style
  264. /// format string \a format.
  265. size_t Printf(const char *format, ...) __attribute__((format(printf, 2, 3)));
  266. /// Output printf formatted output to the stream.
  267. ///
  268. /// Print some formatted output to the stream.
  269. ///
  270. /// \param[in] format
  271. /// A printf style format string.
  272. ///
  273. /// \param[in] args
  274. /// Variable arguments that are needed for the printf style
  275. /// format string \a format.
  276. virtual size_t PrintfVarArg(const char *format, va_list args);
  277. /// Return the OpenOptions for this file.
  278. ///
  279. /// Some options like eOpenOptionDontFollowSymlinks only make
  280. /// sense when a file is being opened (or not at all)
  281. /// and may not be preserved for this method. But any valid
  282. /// File should return either or both of eOpenOptionRead and
  283. /// eOpenOptionWrite here.
  284. ///
  285. /// \return
  286. /// OpenOptions flags for this file, or an error.
  287. virtual llvm::Expected<OpenOptions> GetOptions() const;
  288. llvm::Expected<const char *> GetOpenMode() const {
  289. auto opts = GetOptions();
  290. if (!opts)
  291. return opts.takeError();
  292. return GetStreamOpenModeFromOptions(opts.get());
  293. }
  294. /// Get the permissions for a this file.
  295. ///
  296. /// \return
  297. /// Bits logical OR'ed together from the permission bits defined
  298. /// in lldb_private::File::Permissions.
  299. uint32_t GetPermissions(Status &error) const;
  300. /// Return true if this file is interactive.
  301. ///
  302. /// \return
  303. /// True if this file is a terminal (tty or pty), false
  304. /// otherwise.
  305. bool GetIsInteractive();
  306. /// Return true if this file from a real terminal.
  307. ///
  308. /// Just knowing a file is a interactive isn't enough, we also need to know
  309. /// if the terminal has a width and height so we can do cursor movement and
  310. /// other terminal manipulations by sending escape sequences.
  311. ///
  312. /// \return
  313. /// True if this file is a terminal (tty, not a pty) that has
  314. /// a non-zero width and height, false otherwise.
  315. bool GetIsRealTerminal();
  316. /// Return true if this file is a terminal which supports colors.
  317. ///
  318. /// \return
  319. /// True iff this is a terminal and it supports colors.
  320. bool GetIsTerminalWithColors();
  321. operator bool() const { return IsValid(); };
  322. bool operator!() const { return !IsValid(); };
  323. static char ID;
  324. virtual bool isA(const void *classID) const { return classID == &ID; }
  325. static bool classof(const File *file) { return file->isA(&ID); }
  326. protected:
  327. LazyBool m_is_interactive;
  328. LazyBool m_is_real_terminal;
  329. LazyBool m_supports_colors;
  330. void CalculateInteractiveAndTerminal();
  331. private:
  332. File(const File &) = delete;
  333. const File &operator=(const File &) = delete;
  334. };
  335. class NativeFile : public File {
  336. public:
  337. NativeFile()
  338. : m_descriptor(kInvalidDescriptor), m_own_descriptor(false),
  339. m_stream(kInvalidStream), m_options(), m_own_stream(false) {}
  340. NativeFile(FILE *fh, bool transfer_ownership)
  341. : m_descriptor(kInvalidDescriptor), m_own_descriptor(false), m_stream(fh),
  342. m_options(), m_own_stream(transfer_ownership) {}
  343. NativeFile(int fd, OpenOptions options, bool transfer_ownership)
  344. : m_descriptor(fd), m_own_descriptor(transfer_ownership),
  345. m_stream(kInvalidStream), m_options(options), m_own_stream(false) {}
  346. ~NativeFile() override { Close(); }
  347. bool IsValid() const override {
  348. return DescriptorIsValid() || StreamIsValid();
  349. }
  350. Status Read(void *buf, size_t &num_bytes) override;
  351. Status Write(const void *buf, size_t &num_bytes) override;
  352. Status Close() override;
  353. WaitableHandle GetWaitableHandle() override;
  354. Status GetFileSpec(FileSpec &file_spec) const override;
  355. int GetDescriptor() const override;
  356. FILE *GetStream() override;
  357. off_t SeekFromStart(off_t offset, Status *error_ptr = nullptr) override;
  358. off_t SeekFromCurrent(off_t offset, Status *error_ptr = nullptr) override;
  359. off_t SeekFromEnd(off_t offset, Status *error_ptr = nullptr) override;
  360. Status Read(void *dst, size_t &num_bytes, off_t &offset) override;
  361. Status Write(const void *src, size_t &num_bytes, off_t &offset) override;
  362. Status Flush() override;
  363. Status Sync() override;
  364. size_t PrintfVarArg(const char *format, va_list args) override;
  365. llvm::Expected<OpenOptions> GetOptions() const override;
  366. static char ID;
  367. virtual bool isA(const void *classID) const override {
  368. return classID == &ID || File::isA(classID);
  369. }
  370. static bool classof(const File *file) { return file->isA(&ID); }
  371. protected:
  372. bool DescriptorIsValid() const {
  373. return File::DescriptorIsValid(m_descriptor);
  374. }
  375. bool StreamIsValid() const { return m_stream != kInvalidStream; }
  376. // Member variables
  377. int m_descriptor;
  378. bool m_own_descriptor;
  379. FILE *m_stream;
  380. OpenOptions m_options;
  381. bool m_own_stream;
  382. std::mutex offset_access_mutex;
  383. private:
  384. NativeFile(const NativeFile &) = delete;
  385. const NativeFile &operator=(const NativeFile &) = delete;
  386. };
  387. } // namespace lldb_private
  388. #endif // LLDB_HOST_FILE_H