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