blob: a7b13b09c2be444c2fe5e9ecc362da9dcd80b14a [file] [log] [blame]
Elliott Hughesb4f76162013-09-19 16:27:24 -07001/*
2 * Copyright (C) 2013 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 <unistd.h>
18
Calin Juravled4934a72014-02-24 16:13:50 +000019template<int (*mk_fn)(char*)>
Calin Juravlefe317a32014-02-21 15:11:03 +000020class GenericTemporaryFile {
Elliott Hughesb4f76162013-09-19 16:27:24 -070021 public:
Calin Juravled4934a72014-02-24 16:13:50 +000022 GenericTemporaryFile(const char* dirpath = NULL) {
23 if (dirpath != NULL) {
24 init(dirpath);
25 } else {
26 // Since we might be running on the host or the target, and if we're
27 // running on the host we might be running under bionic or glibc,
28 // let's just try both possible temporary directories and take the
29 // first one that works.
30 init("/data/local/tmp");
31 if (fd == -1) {
32 init("/tmp");
33 }
Elliott Hughes925753a2013-10-18 13:17:18 -070034 }
Elliott Hughesb4f76162013-09-19 16:27:24 -070035 }
36
Calin Juravlefe317a32014-02-21 15:11:03 +000037 ~GenericTemporaryFile() {
Elliott Hughesb4f76162013-09-19 16:27:24 -070038 close(fd);
39 unlink(filename);
40 }
41
42 int fd;
43 char filename[1024];
Elliott Hughes925753a2013-10-18 13:17:18 -070044
45 private:
46 void init(const char* tmp_dir) {
47 snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir);
Calin Juravled4934a72014-02-24 16:13:50 +000048 fd = mk_fn(filename);
Elliott Hughes925753a2013-10-18 13:17:18 -070049 }
Elliott Hughesb4f76162013-09-19 16:27:24 -070050};
Calin Juravlefe317a32014-02-21 15:11:03 +000051
52typedef GenericTemporaryFile<mkstemp> TemporaryFile;
Calin Juravled4934a72014-02-24 16:13:50 +000053
54class TemporaryDir {
55 public:
56 TemporaryDir() {
57 if (!init("/data/local/tmp")) {
58 init("/tmp");
59 }
60 }
61
62 ~TemporaryDir() {
63 rmdir(dirname);
64 }
65
66 char dirname[1024];
67
68 private:
69 bool init(const char* tmp_dir) {
70 snprintf(dirname, sizeof(dirname), "%s/TemporaryDir-XXXXXX", tmp_dir);
71 return (mkdtemp(dirname) != NULL);
72 }
73
74};