blob: c4ee2d5cc314cd5b1566013cd6ecfc5d8b3f9035 [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
Christopher Ferriseda26bc2014-06-12 13:16:36 -070017#include <fcntl.h>
Elliott Hughesb4f76162013-09-19 16:27:24 -070018#include <unistd.h>
19
Calin Juravled4934a72014-02-24 16:13:50 +000020template<int (*mk_fn)(char*)>
Calin Juravlefe317a32014-02-21 15:11:03 +000021class GenericTemporaryFile {
Elliott Hughesb4f76162013-09-19 16:27:24 -070022 public:
Calin Juravled4934a72014-02-24 16:13:50 +000023 GenericTemporaryFile(const char* dirpath = NULL) {
24 if (dirpath != NULL) {
25 init(dirpath);
26 } else {
27 // Since we might be running on the host or the target, and if we're
28 // running on the host we might be running under bionic or glibc,
29 // let's just try both possible temporary directories and take the
30 // first one that works.
31 init("/data/local/tmp");
32 if (fd == -1) {
33 init("/tmp");
34 }
Elliott Hughes925753a2013-10-18 13:17:18 -070035 }
Elliott Hughesb4f76162013-09-19 16:27:24 -070036 }
37
Calin Juravlefe317a32014-02-21 15:11:03 +000038 ~GenericTemporaryFile() {
Elliott Hughesb4f76162013-09-19 16:27:24 -070039 close(fd);
40 unlink(filename);
41 }
42
Christopher Ferriseda26bc2014-06-12 13:16:36 -070043 void reopen() {
44 close(fd);
45 fd = open(filename, O_RDWR);
46 }
47
Elliott Hughesb4f76162013-09-19 16:27:24 -070048 int fd;
49 char filename[1024];
Elliott Hughes925753a2013-10-18 13:17:18 -070050
51 private:
52 void init(const char* tmp_dir) {
53 snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir);
Calin Juravled4934a72014-02-24 16:13:50 +000054 fd = mk_fn(filename);
Elliott Hughes925753a2013-10-18 13:17:18 -070055 }
Elliott Hughesb4f76162013-09-19 16:27:24 -070056};
Calin Juravlefe317a32014-02-21 15:11:03 +000057
58typedef GenericTemporaryFile<mkstemp> TemporaryFile;
Calin Juravled4934a72014-02-24 16:13:50 +000059
60class TemporaryDir {
61 public:
62 TemporaryDir() {
63 if (!init("/data/local/tmp")) {
64 init("/tmp");
65 }
66 }
67
68 ~TemporaryDir() {
69 rmdir(dirname);
70 }
71
72 char dirname[1024];
73
74 private:
75 bool init(const char* tmp_dir) {
76 snprintf(dirname, sizeof(dirname), "%s/TemporaryDir-XXXXXX", tmp_dir);
77 return (mkdtemp(dirname) != NULL);
78 }
79
80};