1 /*
2 * Copyright (C) 2018 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 <fcntl.h>
18 #include <linux/memfd.h>
19 #include <stdio.h>
20 #include <sys/syscall.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23
24 #include "test_util.h"
25
26 namespace android {
27 namespace dm {
28
29 using unique_fd = android::base::unique_fd;
30
31 // Create a temporary in-memory file. If size is non-zero, the file will be
32 // created with a fixed size.
CreateTempFile(const std::string & name,size_t size)33 unique_fd CreateTempFile(const std::string& name, size_t size) {
34 unique_fd fd(syscall(__NR_memfd_create, name.c_str(), MFD_ALLOW_SEALING));
35 if (fd < 0) {
36 return {};
37 }
38 if (size) {
39 if (ftruncate(fd, size) < 0) {
40 perror("ftruncate");
41 return {};
42 }
43 if (fcntl(fd, F_ADD_SEALS, F_SEAL_GROW | F_SEAL_SHRINK) < 0) {
44 perror("fcntl");
45 return {};
46 }
47 }
48 return fd;
49 }
50
51 } // namespace dm
52 } // namespace android
53