1 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2 // -*- mode: C++ -*-
3 //
4 // Copyright 2022 Google LLC
5 //
6 // Licensed under the Apache License v2.0 with LLVM Exceptions (the
7 // "License"); you may not use this file except in compliance with the
8 // License. You may obtain a copy of the License at
9 //
10 // https://llvm.org/LICENSE.txt
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18 // Author: Aleksei Vetrov
19 // Author: Matthias Maennich
20
21 #include "file_descriptor.h"
22
23 #include <fcntl.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 #include <cerrno>
28 #include <exception>
29
30 #include "error.h"
31
32 namespace stg {
33
FileDescriptor(const char * filename,int flags,mode_t mode)34 FileDescriptor::FileDescriptor(const char* filename, int flags, mode_t mode)
35 : fd_(open(filename, flags, mode)) {
36 if (fd_ < 0) {
37 Die() << "open failed: " << Error(errno);
38 }
39 }
40
~FileDescriptor()41 FileDescriptor::~FileDescriptor() noexcept(false) {
42 // If we're unwinding, ignore any close failure.
43 if (fd_ >= 0 && close(fd_) != 0 && std::uncaught_exceptions() == 0) {
44 Die() << "close failed: " << Error(errno);
45 }
46 fd_ = -1;
47 }
48
49
Value() const50 int FileDescriptor::Value() const {
51 Check(fd_ >= 0) << "FileDescriptor was not initialized";
52 return fd_;
53 }
54
55 } // namespace stg
56