blob: 71a9f9b6ec6f474322173af1cad21f40d719ab75 [file] [log] [blame]
Primiano Tucci4f9b6d72017-12-05 20:59:16 +00001/*
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>
Anna Zappone135841c2018-01-16 11:45:15 +000021#include <fcntl.h>
Sami Kyostila26d5cdd2018-01-15 16:42:06 +000022#include <stdio.h>
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000023#include <unistd.h>
24
Anna Zappone135841c2018-01-16 11:45:15 +000025#include <string>
26
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000027#include "perfetto/base/logging.h"
28
29namespace perfetto {
30namespace base {
31
32// RAII classes for auto-releasing fds and dirs.
33template <typename T, int (*CloseFunction)(T), T InvalidValue>
34class ScopedResource {
35 public:
36 explicit ScopedResource(T t = InvalidValue) : t_(t) {}
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 }
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 }
Sami Kyostila26d5cdd2018-01-15 16:42:06 +000056 T release() {
57 T t = t_;
58 t_ = InvalidValue;
59 return t;
60 }
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000061 ~ScopedResource() { reset(InvalidValue); }
62
63 private:
64 ScopedResource(const ScopedResource&) = delete;
65 ScopedResource& operator=(const ScopedResource&) = delete;
66
67 T t_;
68};
69
70using ScopedFile = ScopedResource<int, close, -1>;
Anna Zappone135841c2018-01-16 11:45:15 +000071// Always open a ScopedFile with O-CLOEXEC so we can safely fork and exec.
72inline static ScopedFile OpenFile(const std::string& path, int flags) {
73 ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC));
74 return fd;
75}
76
Sami Kyostila26d5cdd2018-01-15 16:42:06 +000077using ScopedFstream = ScopedResource<FILE*, fclose, nullptr>;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000078using ScopedDir = ScopedResource<DIR*, closedir, nullptr>;
79
80} // namespace base
81} // namespace perfetto
82
83#endif // INCLUDE_PERFETTO_BASE_SCOPED_FILE_H_