aboutsummaryrefslogtreecommitdiff
path: root/unittest_util.h
blob: 4dcfe80401649b51b23a71f5166f7de4734a3b8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* unittest_util.h
 * Copyright 2022 The ChromiumOS Authors
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 *
 * Utility functions for unit tests.
 */

#include <errno.h>
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "util.h"

namespace {

constexpr bool is_android_constexpr() {
#if defined(__ANDROID__)
  return true;
#else
  return false;
#endif
}

// Returns a template path that can be used as an argument to mkstemp / mkdtemp.
constexpr const char* temp_path_pattern() {
  if (is_android_constexpr())
    return "/data/local/tmp/minijail.tests.XXXXXX";
  else
    return "minijail.tests.XXXXXX";
}

// Recursively deletes the subtree rooted at |path|.
bool rmdir_recursive(const std::string& path) {
  auto callback = [](const char* child, const struct stat*, int file_type,
                     struct FTW*) -> int {
    if (file_type == FTW_DP) {
      if (rmdir(child) == -1) {
        fprintf(stderr, "rmdir(%s): %s\n", child, strerror(errno));
        return -1;
      }
    } else if (file_type == FTW_F) {
      if (unlink(child) == -1) {
        fprintf(stderr, "unlink(%s): %s\n", child, strerror(errno));
        return -1;
      }
    }
    return 0;
  };

  return nftw(path.c_str(), callback, 128, FTW_DEPTH) == 0;
}

}  // namespace

// Creates a temporary directory that will be cleaned up upon leaving scope.
class TemporaryDir {
 public:
  TemporaryDir() : path(temp_path_pattern()) {
    if (mkdtemp(const_cast<char*>(path.c_str())) == nullptr)
      path.clear();
  }
  ~TemporaryDir() {
    if (!is_valid())
      return;
    rmdir_recursive(path.c_str());
  }

  bool is_valid() const { return !path.empty(); }

  std::string path;

 private:
  TemporaryDir(const TemporaryDir&) = delete;
  TemporaryDir& operator=(const TemporaryDir&) = delete;
};

// Creates a named temporary file that will be cleaned up upon leaving scope.
class TemporaryFile {
 public:
  TemporaryFile() : path(temp_path_pattern()) {
    int fd = mkstemp(const_cast<char*>(path.c_str()));
    if (fd == -1) {
      path.clear();
      return;
    }
    close(fd);
  }
  ~TemporaryFile() {
    if (!is_valid())
      return;
    unlink(path.c_str());
  }

  bool is_valid() const { return !path.empty(); }

  std::string path;

 private:
  TemporaryFile(const TemporaryFile&) = delete;
  TemporaryFile& operator=(const TemporaryFile&) = delete;
};