• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 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 #include "common/fdsan_fd.h"
17 
18 namespace OHOS {
19 namespace Media {
20 
FdsanFd(int32_t fd)21 FdsanFd::FdsanFd(int32_t fd)
22 {
23     Reset(fd);
24 }
25 
~FdsanFd()26 FdsanFd::~FdsanFd()
27 {
28     Reset();
29 }
30 
FdsanFd(FdsanFd && move)31 FdsanFd::FdsanFd(FdsanFd &&move)
32 {
33     *this = std::move(move);
34 }
35 
operator =(FdsanFd && move)36 FdsanFd &FdsanFd::operator=(FdsanFd &&move)
37 {
38     if (this == &move) {
39         return *this;
40     }
41     Reset();
42     if (move.fd_ != INVALID_FD) {
43         fd_ = move.fd_;
44         move.fd_ = INVALID_FD;
45         // Acquire ownership of the presumably unowned fd.
46         ExchangeTag(fd_, move.Tag(), Tag());
47     }
48     return *this;
49 }
50 
Get() const51 int32_t FdsanFd::Get() const
52 {
53     return fd_;
54 }
55 
Reset(int32_t newFd)56 void FdsanFd::Reset(int32_t newFd)
57 {
58     if (fd_ != INVALID_FD) {
59         Close(fd_, Tag());
60         fd_ = INVALID_FD;
61     }
62     if (newFd != INVALID_FD) {
63         fd_ = newFd;
64         // Acquire ownership of the presumably unowned fd.
65         ExchangeTag(fd_, 0, Tag());
66     }
67 }
68 
69 // Use the address of object as the file tag
Tag()70 uint64_t FdsanFd::Tag()
71 {
72     return reinterpret_cast<uint64_t>(this);
73 }
74 
ExchangeTag(int32_t fd,uint64_t oldTag,uint64_t newTag)75 void FdsanFd::ExchangeTag(int32_t fd, uint64_t oldTag, uint64_t newTag)
76 {
77 #if !defined(CROSS_PLATFORM)
78     if (&fdsan_exchange_owner_tag) {
79         fdsan_exchange_owner_tag(fd, oldTag, newTag);
80     }
81 #endif
82 }
83 
Close(int32_t fd,uint64_t tag)84 int32_t FdsanFd::Close(int32_t fd, uint64_t tag)
85 {
86 #if !defined(CROSS_PLATFORM)
87     if (&fdsan_close_with_tag) {
88         return fdsan_close_with_tag(fd, tag);
89     }
90 #else
91     return close(fd);
92 #endif
93 }
94 
95 }  // namespace Media
96 }  // namespace OHOS