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