blob: 0517bc7138db7a076a5830ac8d7faeb7f68260fc [file] [log] [blame]
Dan Albert58310b42015-03-13 23:06:01 -07001/*
2 * Copyright (C) 2015 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 "test_utils.h"
18
Dan Albert0c4b3a32015-04-29 11:32:23 -070019#include <fcntl.h>
Dan Albert58310b42015-03-13 23:06:01 -070020#include <stdio.h>
21#include <stdlib.h>
Dan Albert0c4b3a32015-04-29 11:32:23 -070022#include <sys/stat.h>
Dan Albert58310b42015-03-13 23:06:01 -070023#include <unistd.h>
24
Dan Albert0c4b3a32015-04-29 11:32:23 -070025#if defined(_WIN32)
26#include <windows.h>
27#endif
28
Dan Albert58310b42015-03-13 23:06:01 -070029TemporaryFile::TemporaryFile() {
Dan Albert0c4b3a32015-04-29 11:32:23 -070030#if defined(__ANDROID__)
Dan Albert58310b42015-03-13 23:06:01 -070031 init("/data/local/tmp");
Dan Albert0c4b3a32015-04-29 11:32:23 -070032#elif defined(_WIN32)
33 char wd[MAX_PATH] = {};
34 _getcwd(wd, sizeof(wd));
35 init(wd);
36#else
37 init("/tmp");
38#endif
Dan Albert58310b42015-03-13 23:06:01 -070039}
40
41TemporaryFile::~TemporaryFile() {
42 close(fd);
43 unlink(filename);
44}
45
46void TemporaryFile::init(const char* tmp_dir) {
47 snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir);
Dan Albert0c4b3a32015-04-29 11:32:23 -070048#if !defined(_WIN32)
Dan Albert58310b42015-03-13 23:06:01 -070049 fd = mkstemp(filename);
Dan Albert0c4b3a32015-04-29 11:32:23 -070050#else
51 // Windows doesn't have mkstemp, and tmpfile creates the file in the root
52 // directory, requiring root (?!) permissions. We have to settle for mktemp.
53 if (mktemp(filename) == nullptr) {
54 abort();
55 }
56
57 fd = open(filename, O_RDWR | O_NOINHERIT | O_CREAT, _S_IREAD | _S_IWRITE);
58#endif
Dan Albert58310b42015-03-13 23:06:01 -070059}