|
| 1 | +#include "tmpfile_hack.hpp" |
| 2 | + |
| 3 | +#include <string> |
| 4 | +#include <optional> |
| 5 | +#include <random> |
| 6 | + |
| 7 | +#include <android/log.h> |
| 8 | + |
| 9 | +#include <cstdlib> |
| 10 | +#include <unistd.h> |
| 11 | + |
| 12 | +static constexpr std::string_view s_filename_template = "tmpfile-XXXXXX"; |
| 13 | +static constexpr std::string_view s_default_directory = "/data/local/tmp"; |
| 14 | + |
| 15 | +static std::optional<std::string> s_tmpfile_directory; |
| 16 | + |
| 17 | +std::string tmpfile_hack::get_tmpfile_directory() { |
| 18 | + if (s_tmpfile_directory.has_value()) { |
| 19 | + return s_tmpfile_directory.value(); |
| 20 | + } |
| 21 | + |
| 22 | + if (const char *tmpfile_directory = std::getenv("TMPDIR"); tmpfile_directory != nullptr) { |
| 23 | + return tmpfile_directory; |
| 24 | + } |
| 25 | + |
| 26 | + return std::string(s_default_directory); |
| 27 | +} |
| 28 | + |
| 29 | +void tmpfile_hack::set_tmpfile_directory(std::string_view tmpfile_dir) { |
| 30 | + s_tmpfile_directory = std::string(tmpfile_dir); |
| 31 | +} |
| 32 | + |
| 33 | +extern "C" { |
| 34 | + |
| 35 | +extern FILE *tmpfile() { |
| 36 | + std::string tmpfile_path = |
| 37 | + tmpfile_hack::get_tmpfile_directory() + "/" + std::string(s_filename_template); |
| 38 | + |
| 39 | + int descriptor = mkstemp(tmpfile_path.data()); |
| 40 | + if (descriptor == -1) { |
| 41 | + __android_log_print(ANDROID_LOG_ERROR, "tmpfile_hack", |
| 42 | + "Failed to create temporary file: %s", tmpfile_path.c_str()); |
| 43 | + return nullptr; |
| 44 | + } |
| 45 | + __android_log_print(ANDROID_LOG_VERBOSE, "tmpfile_hack", "Temporary file created: %s", |
| 46 | + tmpfile_path.c_str()); |
| 47 | + |
| 48 | + FILE *handle = fdopen(descriptor, "w+b"); |
| 49 | + unlink(tmpfile_path.c_str()); |
| 50 | + |
| 51 | + if (handle == nullptr) { |
| 52 | + close(descriptor); |
| 53 | + __android_log_print(ANDROID_LOG_ERROR, "tmpfile_hack", "Failed to open temporary file: %s", |
| 54 | + tmpfile_path.c_str()); |
| 55 | + } |
| 56 | + return handle; |
| 57 | +} |
| 58 | + |
| 59 | +} |
0 commit comments