• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef SMART_FD_H
17 #define SMART_FD_H
18 
19 #include <cstdint>
20 #include <cstdio>
21 #include <unistd.h>
22 
23 namespace OHOS {
24 namespace HiviewDFX {
25 class SmartFd {
26 public:
27     SmartFd() = default;
fd_(fd)28     explicit SmartFd(int fd, bool fdsan = true) : fd_(fd), fdsan_(fdsan)
29     {
30 #ifndef is_host
31         if (fd_ >= 0 && fdsan_) {
32             fdsan_exchange_owner_tag(fd_, 0, fdsan_create_owner_tag(FDSAN_OWNER_TYPE_FILE, DFX_FDSAN_DOMAIN));
33         }
34 #endif // is_host
35     }
36 
~SmartFd()37     ~SmartFd()
38     {
39         Reset();
40     }
41 
42     SmartFd(const SmartFd&) = delete;
43 
44     SmartFd &operator=(const SmartFd&) = delete;
45 
SmartFd(SmartFd && rhs)46     SmartFd(SmartFd&& rhs) noexcept : fd_(rhs.fd_), fdsan_(rhs.fdsan_)
47     {
48         // reset
49         rhs.fd_ = -1;
50         rhs.fdsan_ = false;
51     }
52 
53     SmartFd& operator=(SmartFd&& rhs) noexcept
54     {
55         if (this != &rhs) {
56             CloseFd();
57             fd_ = rhs.fd_;
58             fdsan_ = rhs.fdsan_;
59             // reset
60             rhs.fd_ = -1;
61             rhs.fdsan_ = false;
62         }
63         return *this;
64     }
65 
66     explicit operator bool() const
67     {
68         return fd_ >= 0;
69     }
70 
GetFd()71     int GetFd() const
72     {
73         return fd_;
74     }
75 
Reset()76     void Reset()
77     {
78         CloseFd();
79         fd_ = -1;
80         fdsan_ = false;
81     }
82 
83 private:
CloseFd()84     void CloseFd() const
85     {
86         if (fd_ < 0) {
87             return;
88         }
89 #ifndef is_host
90         if (fdsan_) {
91             fdsan_close_with_tag(fd_, fdsan_create_owner_tag(FDSAN_OWNER_TYPE_FILE, DFX_FDSAN_DOMAIN));
92             return;
93         }
94 #endif // is_host
95         close(fd_);
96     }
97 
98     static constexpr uint64_t DFX_FDSAN_DOMAIN = 0xD002D11;
99     int fd_{-1};
100     bool fdsan_{false};
101 };
102 }
103 }
104 #endif // SMART_FD_H
105