|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | +#include <errno.h> |
| 5 | +#include <sys/stat.h> |
| 6 | +#include <sys/types.h> |
| 7 | +#include <unistd.h> |
| 8 | + |
| 9 | +extern "C" { |
| 10 | + void ultra_sampler_start(); |
| 11 | + |
| 12 | + |
| 13 | + void set_temporary_tmpdir(const char* sub_dir_name, void (*func)()) { |
| 14 | + // Get the current TMPDIR |
| 15 | + const char* original_tmpdir = getenv("TMPDIR"); |
| 16 | + if (!original_tmpdir) { |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + size_t original_tmpdir_len = strlen(original_tmpdir); |
| 21 | + bool has_trailing_slash = original_tmpdir[original_tmpdir_len - 1] == '/'; |
| 22 | + |
| 23 | + // Construct the new TMPDIR path |
| 24 | + size_t new_tmpdir_len = original_tmpdir_len + strlen(sub_dir_name) + 1 + (has_trailing_slash ? 1 : 0); // +1 for '\0', and +1 for the trailing slash |
| 25 | + char* new_tmpdir = (char*)malloc(new_tmpdir_len); |
| 26 | + if (!new_tmpdir) { |
| 27 | + // perror("Failed to allocate memory"); |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + snprintf(new_tmpdir, new_tmpdir_len, has_trailing_slash ? "%s%s/" : "%s/%s/", original_tmpdir, sub_dir_name); |
| 32 | + |
| 33 | + // Create the subdirectory if it doesn't exist |
| 34 | + if (mkdir(new_tmpdir, 0700) != 0 && errno != EEXIST) { |
| 35 | + //perror("Failed to create directory"); |
| 36 | + free(new_tmpdir); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + // Set the TMPDIR environment variable to the new subdirectory |
| 41 | + if (setenv("TMPDIR", new_tmpdir, 1) != 0) { |
| 42 | + //perror("Failed to set TMPDIR"); |
| 43 | + free(new_tmpdir); |
| 44 | + return; |
| 45 | + } |
| 46 | + free(new_tmpdir); |
| 47 | + |
| 48 | + pid_t pid = getpid(); |
| 49 | + printf("Current Process pid: %d tmpdir: %s\n", pid, getenv("TMPDIR")); |
| 50 | + |
| 51 | + // Call the arbitrary function |
| 52 | + func(); |
| 53 | + |
| 54 | + // Restore the original TMPDIR |
| 55 | + setenv("TMPDIR", original_tmpdir, 1); |
| 56 | + } |
| 57 | + |
| 58 | + __attribute__((visibility("default"),used)) |
| 59 | + void ultra_sampler_boot() |
| 60 | + { |
| 61 | + set_temporary_tmpdir(".ultra", ultra_sampler_start); |
| 62 | + } |
| 63 | + |
| 64 | + __attribute__((visibility("default"),used)) |
| 65 | + __attribute__((section("__DATA,__mod_init_func"))) void (*ultra_sampler_boot_ptr)() = &ultra_sampler_boot; |
| 66 | +} |
0 commit comments