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