1 /*
2  * Copyright (C) 2023 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 BERBERIS_NDK_PROGRAM_TESTS_FILE_H_
18 #define BERBERIS_NDK_PROGRAM_TESTS_FILE_H_
19 
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 
InitTempFileTemplate()24 inline const char* InitTempFileTemplate() {
25   // tempnam() is not recommended for use, but we only use it to get the temp dir as it varies on
26   // different platforms. E.g. /tmp on Linux, or /data/local/tmp on Android. The actual file
27   // creation is done by the reliable mkstemp().
28   char* gen_name = tempnam(/* dir */ nullptr, /* prefix */ nullptr);
29   char* template_name;
30   asprintf(&template_name, "%s-ndk-tests-XXXXXX", gen_name);
31   free(gen_name);
32   return template_name;
33 }
34 
TempFileTemplate()35 inline const char* TempFileTemplate() {
36   static const char* kTemplateName = InitTempFileTemplate();
37   return kTemplateName;
38 }
39 
40 class TempFile {
41  public:
TempFile()42   TempFile() {
43     file_name_ = strdup(TempFileTemplate());
44     // Altenatively we could have created a file descriptor by tmpfile() or mkstemp() with the
45     // relative filename, but then there is no portable way to identify the full file name.
46     fd_ = mkstemp(file_name_);
47     if (fd_ < 0) {
48       return;
49     }
50     file_ = fdopen(fd_, "r+");
51   }
52 
~TempFile()53   ~TempFile() {
54     if (file_ != nullptr) {
55       fclose(file_);
56     }
57     unlink(file_name_);
58     free(file_name_);
59   }
60 
get()61   FILE* get() const { return file_; }
62 
fd()63   int fd() const { return fd_; }
64 
FileName()65   const char* FileName() const { return file_name_; }
66 
67  private:
68   FILE* file_ = nullptr;
69   char* file_name_;
70   int fd_;
71 };
72 
73 #endif  // BERBERIS_NDK_PROGRAM_TESTS_FILE_H_
74