1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef INCLUDE_PERFETTO_BASE_SCOPED_FILE_H_
18 #define INCLUDE_PERFETTO_BASE_SCOPED_FILE_H_
19
20 #include <dirent.h>
21 #include <fcntl.h>
22 #include <stdio.h>
23 #include <unistd.h>
24
25 #include <string>
26
27 #include "perfetto/base/logging.h"
28
29 namespace perfetto {
30 namespace base {
31
32 // RAII classes for auto-releasing fds and dirs.
33 template <typename T, int (*CloseFunction)(T), T InvalidValue>
34 class ScopedResource {
35 public:
t_(t)36 explicit ScopedResource(T t = InvalidValue) : t_(t) {}
ScopedResource(ScopedResource && other)37 ScopedResource(ScopedResource&& other) noexcept {
38 t_ = other.t_;
39 other.t_ = InvalidValue;
40 }
41 ScopedResource& operator=(ScopedResource&& other) {
42 reset(other.t_);
43 other.t_ = InvalidValue;
44 return *this;
45 }
get()46 T get() const { return t_; }
47 T operator*() const { return t_; }
48 explicit operator bool() const { return t_ != InvalidValue; }
49 void reset(T r = InvalidValue) {
50 if (t_ != InvalidValue) {
51 int res = CloseFunction(t_);
52 PERFETTO_CHECK(res == 0);
53 }
54 t_ = r;
55 }
release()56 T release() {
57 T t = t_;
58 t_ = InvalidValue;
59 return t;
60 }
~ScopedResource()61 ~ScopedResource() { reset(InvalidValue); }
62
63 private:
64 ScopedResource(const ScopedResource&) = delete;
65 ScopedResource& operator=(const ScopedResource&) = delete;
66
67 T t_;
68 };
69
70 using ScopedFile = ScopedResource<int, close, -1>;
71 // Always open a ScopedFile with O-CLOEXEC so we can safely fork and exec.
OpenFile(const std::string & path,int flags)72 inline static ScopedFile OpenFile(const std::string& path, int flags) {
73 ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC));
74 return fd;
75 }
76
77 using ScopedFstream = ScopedResource<FILE*, fclose, nullptr>;
78 using ScopedDir = ScopedResource<DIR*, closedir, nullptr>;
79
80 } // namespace base
81 } // namespace perfetto
82
83 #endif // INCLUDE_PERFETTO_BASE_SCOPED_FILE_H_
84