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