1 /*
2  * Copyright (C) 2018 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_EXT_BASE_TEMP_FILE_H_
18 #define INCLUDE_PERFETTO_EXT_BASE_TEMP_FILE_H_
19 
20 #include <string>
21 
22 #include "perfetto/ext/base/scoped_file.h"
23 
24 namespace perfetto {
25 namespace base {
26 
27 std::string GetSysTempDir();
28 
29 class TempFile {
30  public:
31   static TempFile CreateUnlinked();
32   static TempFile Create();
33 
34   TempFile(TempFile&&) noexcept;
35   TempFile& operator=(TempFile&&);
36   ~TempFile();
37 
path()38   const std::string& path() const { return path_; }
fd()39   int fd() const { return *fd_; }
40   int operator*() const { return *fd_; }
41 
42   // Unlinks the file from the filesystem but keeps the fd() open.
43   // It is safe to call this multiple times.
44   void Unlink();
45 
46   // Releases the underlying file descriptor. Will unlink the file from the
47   // filesystem if it was created via CreateUnlinked().
48   ScopedFile ReleaseFD();
49 
50  private:
51   TempFile();
52   TempFile(const TempFile&) = delete;
53   TempFile& operator=(const TempFile&) = delete;
54 
55   ScopedFile fd_;
56   std::string path_;
57 };
58 
59 class TempDir {
60  public:
61   static TempDir Create();
62 
63   TempDir(TempDir&&) noexcept;
64   TempDir& operator=(TempDir&&);
65   ~TempDir();
66 
path()67   const std::string& path() const { return path_; }
68 
69  private:
70   TempDir();
71   TempDir(const TempDir&) = delete;
72   TempDir& operator=(const TempDir&) = delete;
73 
74   std::string path_;
75 };
76 
77 }  // namespace base
78 }  // namespace perfetto
79 
80 #endif  // INCLUDE_PERFETTO_EXT_BASE_TEMP_FILE_H_
81