1 //===-- FileAction.cpp ------------------------------------------*- 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 
9 #include <fcntl.h>
10 
11 #include "lldb/Host/FileAction.h"
12 #include "lldb/Host/PosixApi.h"
13 #include "lldb/Utility/Stream.h"
14 
15 using namespace lldb_private;
16 
17 //----------------------------------------------------------------------------
18 // FileAction member functions
19 //----------------------------------------------------------------------------
20 
21 FileAction::FileAction()
22     : m_action(eFileActionNone), m_fd(-1), m_arg(-1), m_file_spec() {}
23 
24 void FileAction::Clear() {
25   m_action = eFileActionNone;
26   m_fd = -1;
27   m_arg = -1;
28   m_file_spec.Clear();
29 }
30 
31 llvm::StringRef FileAction::GetPath() const { return m_file_spec.GetCString(); }
32 
33 const FileSpec &FileAction::GetFileSpec() const { return m_file_spec; }
34 
35 bool FileAction::Open(int fd, const FileSpec &file_spec, bool read,
36                       bool write) {
37   if ((read || write) && fd >= 0 && file_spec) {
38     m_action = eFileActionOpen;
39     m_fd = fd;
40     if (read && write)
41       m_arg = O_NOCTTY | O_CREAT | O_RDWR;
42     else if (read)
43       m_arg = O_NOCTTY | O_RDONLY;
44     else
45       m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
46     m_file_spec = file_spec;
47     return true;
48   } else {
49     Clear();
50   }
51   return false;
52 }
53 
54 bool FileAction::Close(int fd) {
55   Clear();
56   if (fd >= 0) {
57     m_action = eFileActionClose;
58     m_fd = fd;
59   }
60   return m_fd >= 0;
61 }
62 
63 bool FileAction::Duplicate(int fd, int dup_fd) {
64   Clear();
65   if (fd >= 0 && dup_fd >= 0) {
66     m_action = eFileActionDuplicate;
67     m_fd = fd;
68     m_arg = dup_fd;
69   }
70   return m_fd >= 0;
71 }
72 
73 void FileAction::Dump(Stream &stream) const {
74   stream.PutCString("file action: ");
75   switch (m_action) {
76   case eFileActionClose:
77     stream.Printf("close fd %d", m_fd);
78     break;
79   case eFileActionDuplicate:
80     stream.Printf("duplicate fd %d to %d", m_fd, m_arg);
81     break;
82   case eFileActionNone:
83     stream.PutCString("no action");
84     break;
85   case eFileActionOpen:
86     stream.Printf("open fd %d with '%s', OFLAGS = 0x%x", m_fd,
87                   m_file_spec.GetCString(), m_arg);
88     break;
89   }
90 }
91