• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "perfetto/base/temp_file.h"
18 
19 #include <stdlib.h>
20 #include <unistd.h>
21 
22 namespace perfetto {
23 namespace base {
24 
25 namespace {
26 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
27 constexpr char kSysTmpPath[] = "/data/local/tmp";
28 #else
29 constexpr char kSysTmpPath[] = "/tmp";
30 #endif
31 }  // namespace
32 
33 // static
Create()34 TempFile TempFile::Create() {
35   TempFile temp_file;
36   const char* tmpdir = getenv("TMPDIR");
37   if (tmpdir) {
38     temp_file.path_.assign(tmpdir);
39   } else {
40     temp_file.path_.assign(kSysTmpPath);
41   }
42   temp_file.path_.append("/perfetto-XXXXXXXX");
43   temp_file.fd_.reset(mkstemp(&temp_file.path_[0]));
44   PERFETTO_CHECK(temp_file.fd_);
45   return temp_file;
46 }
47 
48 // static
CreateUnlinked()49 TempFile TempFile::CreateUnlinked() {
50   TempFile temp_file = TempFile::Create();
51   temp_file.Unlink();
52   return temp_file;
53 }
54 
55 TempFile::TempFile() = default;
56 
~TempFile()57 TempFile::~TempFile() {
58   Unlink();
59 }
60 
ReleaseFD()61 ScopedFile TempFile::ReleaseFD() {
62   Unlink();
63   return std::move(fd_);
64 }
65 
Unlink()66 void TempFile::Unlink() {
67   if (path_.empty())
68     return;
69   PERFETTO_CHECK(unlink(path_.c_str()) == 0);
70   path_.clear();
71 }
72 
73 TempFile::TempFile(TempFile&&) noexcept = default;
74 TempFile& TempFile::operator=(TempFile&&) = default;
75 
76 // static
Create()77 TempDir TempDir::Create() {
78   TempDir temp_dir;
79   temp_dir.path_.assign(kSysTmpPath);
80   temp_dir.path_.append("/perfetto-XXXXXXXX");
81   PERFETTO_CHECK(mkdtemp(&temp_dir.path_[0]));
82   return temp_dir;
83 }
84 
85 TempDir::TempDir() = default;
86 
~TempDir()87 TempDir::~TempDir() {
88   PERFETTO_CHECK(rmdir(path_.c_str()) == 0);
89 }
90 
91 }  // namespace base
92 }  // namespace perfetto
93