Build tool
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sys.cc 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. #include "sys.h"
  2. #include <libgen.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <unistd.h>
  6. #include <dirent.h>
  7. #include <string.h>
  8. #include <errno.h>
  9. #include <sys/types.h>
  10. #include <sys/wait.h>
  11. #include <stdexcept>
  12. #include <system_error>
  13. #include <unordered_set>
  14. #include <atomic>
  15. #include "logger.h"
  16. #include "globals.h"
  17. namespace sys {
  18. static thread_local std::unordered_set<std::string> mkdirp_set;
  19. static std::atomic<int> signalCounter(0);
  20. struct SigCtx {
  21. SigCtx(bool enabled): enabled(enabled) {
  22. if (enabled && signalCounter++ == 0) {
  23. signal(SIGINT, SIG_IGN);
  24. }
  25. }
  26. ~SigCtx() {
  27. if (enabled && --signalCounter == 0) {
  28. signal(SIGINT, SIG_DFL);
  29. }
  30. }
  31. bool enabled;
  32. };
  33. std::string sanitizePath(const std::string &path) {
  34. std::string npath;
  35. size_t idx = 0;
  36. while (idx < path.size()) {
  37. if (idx >= path.size() - 2) {
  38. npath += path[idx++];
  39. } else if (path[idx] == '.' && path[idx + 1] == '.' && path[idx + 2] == '/') {
  40. npath += "__parent__/";
  41. idx += 3;
  42. } else {
  43. npath += path[idx++];
  44. }
  45. }
  46. if (npath[npath.size() - 1] == '.' && npath[npath.size() - 2] == '.') {
  47. npath.replace(npath.size() - 2, 2, "__parent__");
  48. }
  49. return npath;
  50. }
  51. FileInfo fileInfo(const std::string &path) {
  52. FileInfo finfo;
  53. struct stat st;
  54. if (stat(path.c_str(), &st) < 0) {
  55. throw std::runtime_error("stat '" + path + "': " + strerror(errno));
  56. }
  57. finfo.mTimeSec = st.st_mtim.tv_sec;
  58. finfo.mTimeNsec = st.st_mtim.tv_nsec;
  59. finfo.isDir = S_ISDIR(st.st_mode);
  60. return finfo;
  61. }
  62. bool fileExists(const std::string &path) {
  63. struct stat st;
  64. if (stat(path.c_str(), &st) < 0) {
  65. if (errno == ENOENT) {
  66. return false;
  67. } else {
  68. throw std::runtime_error("stat '" + path + "': " + strerror(errno));
  69. }
  70. }
  71. return true;
  72. }
  73. void mkdirp(const std::string &path) {
  74. auto res = mkdirp_set.emplace(path);
  75. if (!res.second)
  76. return;
  77. // TODO: Implement this in C++ instead
  78. std::vector<std::string> argv;
  79. argv.push_back("mkdir");
  80. argv.push_back("-p");
  81. argv.push_back("--");
  82. argv.push_back(path);
  83. ProcConf conf;
  84. conf.print = global::verbose >= 2;
  85. execute(argv, conf);
  86. }
  87. void rmrf(const std::string &path) {
  88. mkdirp_set.erase(path);
  89. // TODO: Implement this in C++ instead
  90. std::vector<std::string> argv;
  91. argv.push_back("rm");
  92. argv.push_back("-rf");
  93. argv.push_back("--");
  94. argv.push_back(path);
  95. ProcConf conf;
  96. conf.print = global::verbose >= 2;
  97. execute(argv, conf);
  98. }
  99. void execute(const std::vector<std::string> &args, const ProcConf &conf) {
  100. if (conf.print) {
  101. std::string str;
  102. for (size_t i = 0; i < args.size(); ++i) {
  103. if (i != 0) {
  104. str += " ";
  105. }
  106. str += args[i];
  107. }
  108. logger::log(str);
  109. }
  110. // argv[0] should be interpreted as a shell command, because being able to run
  111. // CC='gcc --sysroot=/blah' is used by some systems.
  112. std::string command = std::string(args[0]) + " \"$@\"";
  113. static thread_local std::vector<const char *> argv;
  114. argv.clear();
  115. argv.push_back("/bin/sh"); // TODO: Use $SHELL?
  116. argv.push_back("-c");
  117. argv.push_back(command.c_str());
  118. argv.push_back("--");
  119. for (size_t i = 1; i < args.size(); ++i) {
  120. argv.push_back(args[i].c_str());
  121. }
  122. argv.push_back(nullptr);
  123. int stdoutPipe[2];
  124. if (conf.output == nullptr) {
  125. stdoutPipe[1] = STDOUT_FILENO;
  126. } else {
  127. if (pipe(stdoutPipe) < 0) {
  128. throw std::runtime_error(std::string("pipe: ") + strerror(errno));
  129. }
  130. }
  131. SigCtx sigCtx(conf.forwardSignals);
  132. pid_t child = fork();
  133. if (child == 0) {
  134. signal(SIGINT, SIG_DFL);
  135. if (conf.output != nullptr) {
  136. close(stdoutPipe[0]);
  137. dup2(stdoutPipe[1], 1);
  138. }
  139. // So, from what I've read, execvp should never modify its argv; so this should be fine?
  140. if (execvp(argv[0], (char *const *)argv.data()) < 0) {
  141. perror(argv[0]);
  142. abort();
  143. }
  144. // This shouldn't happen
  145. abort();
  146. } else if (child < 0) {
  147. throw std::runtime_error(std::string("fork: ") + strerror(errno));
  148. }
  149. if (conf.output != nullptr) {
  150. close(stdoutPipe[1]);
  151. char buf[1025];
  152. while (true) {
  153. ssize_t num = read(stdoutPipe[0], buf, sizeof(buf) - 1);
  154. if (num < 0 && errno != EAGAIN) {
  155. close(stdoutPipe[0]);
  156. throw std::runtime_error(
  157. std::string("read: ") + strerror(errno) +
  158. " (fd: " + std::to_string(stdoutPipe[0]) + ")");
  159. } else if (num < 0) {
  160. continue;
  161. }
  162. if (num == 0) {
  163. close(stdoutPipe[0]);
  164. break;
  165. }
  166. buf[num] = '\0';
  167. *conf.output += buf;
  168. }
  169. }
  170. int wstatus;
  171. waitpid(child, &wstatus, 0);
  172. if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != 0) {
  173. throw std::runtime_error(std::string(args[0]) +
  174. " exited with code " + std::to_string(WEXITSTATUS(wstatus)));
  175. }
  176. if (WTERMSIG(wstatus)) {
  177. throw std::runtime_error(std::string(args[0]) +
  178. " terminated due to " + strsignal(WTERMSIG(wstatus)));
  179. }
  180. if (conf.output != nullptr && conf.output->back() == '\n') {
  181. conf.output->pop_back();
  182. }
  183. }
  184. void readDir(const std::string &path, std::vector<std::string> &files) {
  185. DIR *d = opendir(path.c_str());
  186. if (d == NULL) {
  187. throw std::runtime_error("opendir '" + path + "': " + strerror(errno));
  188. }
  189. struct dirent *ent;
  190. while ((ent = readdir(d)) != NULL) {
  191. if (ent->d_name[0] == '.')
  192. continue;
  193. files.emplace_back(ent->d_name);
  194. }
  195. closedir(d);
  196. }
  197. void chdir(const std::string &path) {
  198. if (::chdir(path.c_str()) < 0) {
  199. throw std::runtime_error("chdir '" + path + "': " + strerror(errno));
  200. }
  201. }
  202. std::string cwd() {
  203. std::vector<char> buf;
  204. buf.reserve(128);
  205. while (1) {
  206. char *res = getcwd(buf.data(), buf.capacity());
  207. if (res == NULL) {
  208. if (errno == ERANGE) {
  209. buf.reserve(buf.capacity() * 2);
  210. } else {
  211. throw std::system_error(EFAULT, std::generic_category());
  212. }
  213. } else {
  214. std::string str(buf.data());
  215. return str;
  216. }
  217. }
  218. }
  219. void symlink(const std::string &from, const std::string &to) {
  220. // TODO: Implement this in C++ instead
  221. std::vector<std::string> argv;
  222. argv.push_back("ln");
  223. argv.push_back("-s");
  224. argv.push_back("-f");
  225. argv.push_back("--");
  226. argv.push_back(from);
  227. argv.push_back(to);
  228. sys::execute(argv, ProcConf{});
  229. }
  230. std::string dirname(const std::string &path) {
  231. std::vector<char> buf(path.begin(), path.end());
  232. buf.push_back('\0');
  233. char *dir = ::dirname(buf.data());
  234. return std::string(dir);
  235. }
  236. }