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