fileAPI.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2020 to 2022 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. #include "fileAPI.h"
  24. #ifdef USE_MICROSOFT_WINDOWS
  25. // Headers for MS-Windows.
  26. #include <windows.h>
  27. #include <synchapi.h>
  28. #else
  29. // Headers for Posix compliant systems.
  30. #include <unistd.h>
  31. #include <spawn.h>
  32. #include <sys/wait.h>
  33. #include <sys/stat.h>
  34. #include <dirent.h>
  35. // The environment flags contain information such as username, language, color settings, which system shell and window manager is used...
  36. extern char **environ;
  37. #endif
  38. #ifdef USE_MACOS
  39. // Headers for MacOS.
  40. #include <libproc.h>
  41. #endif
  42. #include <fstream>
  43. #include <cstdlib>
  44. #include "bufferAPI.h"
  45. #include "../base/virtualStack.h"
  46. namespace dsr {
  47. constexpr const char32_t* getPathSeparator(PathSyntax pathSyntax) {
  48. if (pathSyntax == PathSyntax::Windows) {
  49. return U"\\";
  50. } else if (pathSyntax == PathSyntax::Posix) {
  51. return U"/";
  52. } else {
  53. return U"?";
  54. }
  55. }
  56. #ifdef USE_MICROSOFT_WINDOWS
  57. using NativeChar = wchar_t; // UTF-16
  58. static const CharacterEncoding nativeEncoding = CharacterEncoding::BOM_UTF16LE;
  59. #define FILE_ACCESS_FUNCTION _wfopen
  60. #define FILE_ACCESS_SELECTION (write ? L"wb" : L"rb")
  61. List<String> file_impl_getInputArguments() {
  62. // Get a pointer to static memory with the command
  63. LPWSTR cmd = GetCommandLineW();
  64. // Split the arguments into an array of arguments
  65. int argc = 0;
  66. LPWSTR *argv = CommandLineToArgvW(cmd, &argc);
  67. // Convert the arguments into dsr::List<dsr::String>
  68. List<String> args = file_impl_convertInputArguments(argc, (void**)argv);
  69. // Free the native list of arguments
  70. LocalFree(argv);
  71. return args;
  72. }
  73. #else
  74. using NativeChar = char; // UTF-8
  75. static const CharacterEncoding nativeEncoding = CharacterEncoding::BOM_UTF8;
  76. #define FILE_ACCESS_FUNCTION fopen
  77. #define FILE_ACCESS_SELECTION (write ? "wb" : "rb")
  78. List<String> file_impl_getInputArguments() { return List<String>(); }
  79. #endif
  80. // Length of fixed size buffers.
  81. const int maxLength = 512;
  82. static const NativeChar* toNativeString(const ReadableString &filename, Buffer &buffer) {
  83. buffer = string_saveToMemory(filename, nativeEncoding, LineEncoding::CrLf, false, true);
  84. return (const NativeChar*)buffer_dangerous_getUnsafeData(buffer);
  85. }
  86. static String fromNativeString(const NativeChar *text) {
  87. return string_dangerous_decodeFromData(text, nativeEncoding);
  88. }
  89. List<String> file_impl_convertInputArguments(int argn, void **argv) {
  90. List<String> result;
  91. result.reserve(argn);
  92. for (int a = 0; a < argn; a++) {
  93. result.push(fromNativeString((NativeChar*)(argv[a])));
  94. }
  95. return result;
  96. }
  97. static FILE* accessFile(const ReadableString &filename, bool write) {
  98. Buffer buffer;
  99. return FILE_ACCESS_FUNCTION(toNativeString(filename, buffer), FILE_ACCESS_SELECTION);
  100. }
  101. Buffer file_loadBuffer(const ReadableString& filename, bool mustExist) {
  102. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  103. FILE *file = accessFile(modifiedFilename, false);
  104. if (file != nullptr) {
  105. // Get the file's size by going to the end, measuring, and going back
  106. fseek(file, 0L, SEEK_END);
  107. uintptr_t fileSize = ftell(file);
  108. rewind(file);
  109. // Allocate a buffer of the file's size
  110. Buffer buffer = buffer_create(fileSize);
  111. size_t resultSize = fread((void*)buffer_dangerous_getUnsafeData(buffer), fileSize, 1, file);
  112. // Supress warnings.
  113. (void)resultSize;
  114. fclose(file);
  115. return buffer;
  116. } else {
  117. if (mustExist) {
  118. throwError(U"Failed to load ", modifiedFilename, U".\n");
  119. }
  120. // If the file cound not be found and opened, an empty buffer is returned
  121. return Buffer();
  122. }
  123. }
  124. bool file_saveBuffer(const ReadableString& filename, Buffer buffer, bool mustWork) {
  125. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  126. if (!buffer_exists(buffer)) {
  127. if (mustWork) {
  128. throwError(U"buffer_save: Can't save a buffer that don't exist to a file.\n");
  129. }
  130. return false;
  131. } else {
  132. FILE *file = accessFile(modifiedFilename, true);
  133. if (file != nullptr) {
  134. fwrite((void*)buffer_dangerous_getUnsafeData(buffer), buffer_getSize(buffer), 1, file);
  135. fclose(file);
  136. } else {
  137. if (mustWork) {
  138. throwError(U"Failed to save ", modifiedFilename, U".\n");
  139. }
  140. return false;
  141. }
  142. }
  143. // Success if there are no errors.
  144. return true;
  145. }
  146. const char32_t* file_separator(PathSyntax pathSyntax) {
  147. return getPathSeparator(pathSyntax);
  148. }
  149. bool file_isSeparator(DsrChar c) {
  150. return c == U'\\' || c == U'/';
  151. }
  152. // Returns the index of the first / or \ in path, or defaultIndex if none existed.
  153. int64_t file_findFirstSeparator(const ReadableString &path, int64_t defaultIndex, int64_t startIndex) {
  154. for (int64_t i = startIndex; i < string_length(path); i++) {
  155. DsrChar c = path[i];
  156. if (file_isSeparator(c)) {
  157. return i;
  158. }
  159. }
  160. return defaultIndex;
  161. }
  162. // Returns the index of the last / or \ in path, or defaultIndex if none existed.
  163. int64_t file_findLastSeparator(const ReadableString &path, int64_t defaultIndex) {
  164. for (int64_t i = string_length(path) - 1; i >= 0; i--) {
  165. DsrChar c = path[i];
  166. if (file_isSeparator(c)) {
  167. return i;
  168. }
  169. }
  170. return defaultIndex;
  171. }
  172. String file_optimizePath(const ReadableString &path, PathSyntax pathSyntax) {
  173. String result; // The final output being appended.
  174. String currentEntry; // The current entry.
  175. bool hadSeparator = false;
  176. bool hadContent = false;
  177. int64_t inputLength = string_length(path);
  178. string_reserve(result, inputLength);
  179. // Read null terminator from one element outside of the path to allow concluding an entry not followed by any separator.
  180. // The null terminator is not actually stored, but reading out of bound gives a null terminator.
  181. for (int64_t i = 0; i <= inputLength; i++) {
  182. DsrChar c = path[i];
  183. bool separator = file_isSeparator(c);
  184. if (separator || i == inputLength) {
  185. bool appendEntry = true;
  186. bool appendSeparator = separator;
  187. if (hadSeparator) {
  188. if (hadContent && string_length(currentEntry) == 0) {
  189. // Reduce non-leading // into / by skipping "" entries.
  190. // Any leading multiples of slashes have their count preserved, because some systems use them to indicate special use cases.
  191. appendEntry = false;
  192. appendSeparator = false;
  193. } else if (string_match(currentEntry, U".")) {
  194. // Reduce /./ into / by skipping "." entries.
  195. appendEntry = false;
  196. appendSeparator = false;
  197. } else if (string_match(currentEntry, U"..")) {
  198. // Reduce the parent directory against the reverse ".." entry.
  199. result = file_getRelativeParentFolder(result, pathSyntax);
  200. if (string_match(result, U"?")) {
  201. return U"?";
  202. }
  203. appendEntry = false;
  204. }
  205. }
  206. if (appendEntry) {
  207. string_append(result, string_removeOuterWhiteSpace(currentEntry));
  208. }
  209. if (appendSeparator) {
  210. string_append(result, getPathSeparator(pathSyntax));
  211. }
  212. currentEntry = U"";
  213. if (separator) {
  214. hadSeparator = true;
  215. }
  216. } else {
  217. string_appendChar(currentEntry, c);
  218. hadContent = true;
  219. }
  220. }
  221. // Remove trailing separators if we had content.
  222. if (hadSeparator && hadContent) {
  223. int64_t lastNonSeparator = -1;
  224. for (int64_t i = string_length(result) - 1; i >= 0; i--) {
  225. if (!file_isSeparator(result[i])) {
  226. lastNonSeparator = i;
  227. break;
  228. }
  229. }
  230. result = string_until(result, lastNonSeparator);
  231. }
  232. return result;
  233. }
  234. ReadableString file_getPathlessName(const ReadableString &path) {
  235. return string_after(path, file_findLastSeparator(path));
  236. }
  237. bool file_hasExtension(const String& path) {
  238. int64_t lastDotIndex = string_findLast(path, U'.');
  239. int64_t lastSeparatorIndex = file_findLastSeparator(path);
  240. if (lastDotIndex != -1 && lastSeparatorIndex < lastDotIndex) {
  241. return true;
  242. } else {
  243. return false;
  244. }
  245. }
  246. ReadableString file_getExtension(const String& filename) {
  247. int64_t lastDotIndex = string_findLast(filename, U'.');
  248. int64_t lastSeparatorIndex = file_findLastSeparator(filename);
  249. // Only use the last dot if there is no folder separator after it.
  250. if (lastDotIndex != -1 && lastSeparatorIndex < lastDotIndex) {
  251. return string_removeOuterWhiteSpace(string_after(filename, lastDotIndex));
  252. } else {
  253. return U"";
  254. }
  255. }
  256. ReadableString file_getExtensionless(const String& filename) {
  257. int64_t lastDotIndex = string_findLast(filename, U'.');
  258. int64_t lastSeparatorIndex = file_findLastSeparator(filename);
  259. // Only use the last dot if there is no folder separator after it.
  260. if (lastDotIndex != -1 && lastSeparatorIndex < lastDotIndex) {
  261. return string_removeOuterWhiteSpace(string_before(filename, lastDotIndex));
  262. } else {
  263. return string_removeOuterWhiteSpace(filename);
  264. }
  265. }
  266. String file_getRelativeParentFolder(const ReadableString &path, PathSyntax pathSyntax) {
  267. String optimizedPath = file_optimizePath(path, pathSyntax);
  268. if (string_length(optimizedPath) == 0) {
  269. // Use .. to go outside of the current directory.
  270. return U"..";
  271. } else if (string_match(file_getPathlessName(optimizedPath), U"?")) {
  272. // From unknown to unknown.
  273. return U"?";
  274. } else if (file_isRoot(optimizedPath, false, pathSyntax)) {
  275. // If it's the known true root, then we know that it does not have a parent and must fail.
  276. return U"?";
  277. } else if (file_isRoot(optimizedPath, true, pathSyntax)) {
  278. // If it's an alias for an arbitrary folder, use .. to leave it.
  279. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  280. } else if (string_match(file_getPathlessName(optimizedPath), U"..")) {
  281. // Add more dots to the path.
  282. return file_combinePaths(optimizedPath, U"..", pathSyntax);
  283. } else {
  284. // Inside of something.
  285. int64_t lastSeparator = file_findLastSeparator(optimizedPath, 0);
  286. if (pathSyntax == PathSyntax::Windows) {
  287. // Return everything before the last separator.
  288. return string_before(optimizedPath, lastSeparator);
  289. } else { // PathSyntax::Posix
  290. if (file_hasRoot(path, false, pathSyntax) && lastSeparator == 0) {
  291. // Keep the absolute root.
  292. return U"/";
  293. } else {
  294. // Keep everything before the last separator.
  295. return string_before(optimizedPath, lastSeparator);
  296. }
  297. }
  298. }
  299. }
  300. String file_getTheoreticalAbsoluteParentFolder(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  301. if (file_hasRoot(path, true, LOCAL_PATH_SYNTAX)) {
  302. // Absolute paths should be treated the same as a theoretical path.
  303. return file_getRelativeParentFolder(path, pathSyntax);
  304. } else {
  305. // If the input is not absolute, convert it before taking the parent directory.
  306. return file_getRelativeParentFolder(file_getTheoreticalAbsolutePath(path, currentPath, pathSyntax), pathSyntax);
  307. }
  308. }
  309. String file_getAbsoluteParentFolder(const ReadableString &path) {
  310. return file_getTheoreticalAbsoluteParentFolder(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  311. }
  312. bool file_isRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  313. ReadableString cleanPath = string_removeOuterWhiteSpace(path);
  314. int64_t length = string_length(cleanPath);
  315. if (length == 0) {
  316. // Relative path is not a root.
  317. return false;
  318. } else if (length == 1) {
  319. DsrChar c = cleanPath[0];
  320. if (pathSyntax == PathSyntax::Windows) {
  321. return c == U'\\'; // Implicit drive root.
  322. } else { // PathSyntax::Posix
  323. return c == U'/' || (c == U'~' && treatHomeFolderAsRoot); // Root over all drives or home folder.
  324. }
  325. } else {
  326. if (pathSyntax == PathSyntax::Windows && cleanPath[length - 1] == U':') {
  327. // C:, D:, ...
  328. return true;
  329. } else {
  330. return false;
  331. }
  332. }
  333. }
  334. bool file_hasRoot(const ReadableString &path, bool treatHomeFolderAsRoot, PathSyntax pathSyntax) {
  335. int64_t firstSeparator = file_findFirstSeparator(path);
  336. if (firstSeparator == -1) {
  337. // If there is no separator, path has a root if it is a root.
  338. return file_isRoot(path, treatHomeFolderAsRoot, pathSyntax);
  339. } else if (firstSeparator == 0) {
  340. // Starting with a separator. Either an implicit drive on Windows or the whole system's root on Posix.
  341. return true;
  342. } else {
  343. // Has a root if the first entry before the first slash is a root.
  344. return file_isRoot(string_before(path, firstSeparator), treatHomeFolderAsRoot, pathSyntax);
  345. }
  346. }
  347. bool file_setCurrentPath(const ReadableString &path) {
  348. Buffer buffer;
  349. const NativeChar *nativePath = toNativeString(file_optimizePath(path, LOCAL_PATH_SYNTAX), buffer);
  350. #ifdef USE_MICROSOFT_WINDOWS
  351. return SetCurrentDirectoryW(nativePath) != 0;
  352. #else
  353. return chdir(nativePath) == 0;
  354. #endif
  355. }
  356. String file_getCurrentPath() {
  357. #ifdef USE_MICROSOFT_WINDOWS
  358. NativeChar resultBuffer[maxLength + 1] = {0};
  359. GetCurrentDirectoryW(maxLength, resultBuffer);
  360. return fromNativeString(resultBuffer);
  361. #else
  362. NativeChar resultBuffer[maxLength + 1] = {0};
  363. char* result = getcwd(resultBuffer, maxLength);
  364. // Supress warnings about not using the result, because we already have it in the buffer.
  365. (void)result;
  366. return fromNativeString(resultBuffer);
  367. #endif
  368. }
  369. String file_followSymbolicLink(const ReadableString &path, bool mustExist) {
  370. #ifdef USE_MICROSOFT_WINDOWS
  371. // TODO: Is there anything that can be used as a symbolic link on Windows?
  372. #else
  373. String modifiedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  374. Buffer buffer;
  375. const NativeChar *nativePath = toNativeString(modifiedPath, buffer);
  376. NativeChar resultBuffer[maxLength + 1] = {0};
  377. if (readlink(nativePath, resultBuffer, maxLength) != -1) {
  378. return fromNativeString(resultBuffer);
  379. }
  380. #endif
  381. if (mustExist) { throwError(U"The symbolic link ", path, U" could not be found!\n"); }
  382. return U"?";
  383. }
  384. String file_getApplicationFolder(bool allowFallback) {
  385. #if defined(USE_MICROSOFT_WINDOWS)
  386. NativeChar resultBuffer[maxLength + 1] = {0};
  387. GetModuleFileNameW(nullptr, resultBuffer, maxLength);
  388. return file_getRelativeParentFolder(fromNativeString(resultBuffer), LOCAL_PATH_SYNTAX);
  389. #elif defined(USE_MACOS)
  390. // Get the process identifier.
  391. pid_t pid = getpid();
  392. char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
  393. // Get the process file path.
  394. size_t size = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
  395. if (size != 0) {
  396. // If it worked, get its parent directory.
  397. return file_getAbsoluteParentFolder(string_dangerous_decodeFromData(pathbuf, CharacterEncoding::BOM_UTF8));
  398. } else if (allowFallback) {
  399. // If it failed, use a fallback result if allowed by the caller.
  400. return file_getCurrentPath();
  401. } else {
  402. throwError(U"file_getApplicationFolder failed and was not allowed to fall back on the current folder!\n");
  403. return U"";
  404. }
  405. #else
  406. NativeChar resultBuffer[maxLength + 1] = {0};
  407. if (readlink("/proc/self/exe", resultBuffer, maxLength) != -1) {
  408. // Linux detected
  409. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  410. } else if (readlink("/proc/curproc/file", resultBuffer, maxLength) != -1) {
  411. // BSD detected
  412. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  413. } else if (readlink("/proc/self/path/a.out", resultBuffer, maxLength) != -1) {
  414. // Solaris detected
  415. return file_getAbsoluteParentFolder(fromNativeString(resultBuffer));
  416. } else if (allowFallback) {
  417. return file_getCurrentPath();
  418. } else {
  419. throwError(U"file_getApplicationFolder is not implemented for the current system!\n");
  420. return U"";
  421. }
  422. #endif
  423. }
  424. String file_combinePaths(const ReadableString &a, const ReadableString &b, PathSyntax pathSyntax) {
  425. ReadableString cleanA = string_removeOuterWhiteSpace(a);
  426. ReadableString cleanB = string_removeOuterWhiteSpace(b);
  427. int64_t lengthA = string_length(cleanA);
  428. int64_t lengthB = string_length(cleanB);
  429. if (file_hasRoot(b, true, pathSyntax)) {
  430. // Restarting from root or home folder.
  431. return cleanB;
  432. } else if (lengthA == 0) {
  433. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  434. return cleanB;
  435. } else if (lengthB == 0) {
  436. // Ignoring initial relative path, so that relative paths are not suddenly moved to the root by a new separator.
  437. return cleanA;
  438. } else {
  439. if (file_isSeparator(a[lengthA - 1])) {
  440. // Already ending with a separator.
  441. return string_combine(cleanA, cleanB);
  442. } else {
  443. // Combine using a separator.
  444. return string_combine(cleanA, getPathSeparator(pathSyntax), cleanB);
  445. }
  446. }
  447. }
  448. // Returns path with the drive letter applied from currentPath if missing in path.
  449. // Used for converting drive relative paths into true absolute paths on MS-Windows.
  450. static String applyDriveLetter(const ReadableString &path, const ReadableString &currentPath) {
  451. // Convert implicit drive into a named drive.
  452. if (path[0] == U'\\') {
  453. int64_t colonIndex = string_findFirst(currentPath, U':', -1);
  454. if (colonIndex == -1) {
  455. return U"?";
  456. } else {
  457. // Get the drive letter from the current path.
  458. String drive = string_until(currentPath, colonIndex);
  459. return string_combine(drive, path);
  460. }
  461. } else {
  462. // Already absolute.
  463. return path;
  464. }
  465. }
  466. String file_getTheoreticalAbsolutePath(const ReadableString &path, const ReadableString &currentPath, PathSyntax pathSyntax) {
  467. // Home folders are absolute enough, because we don't want to lose the account ambiguity by mangling it into hardcoded usernames.
  468. if (file_hasRoot(path, true, pathSyntax)) {
  469. if (pathSyntax == PathSyntax::Windows) {
  470. // Make sure that no drive letter is missing.
  471. return applyDriveLetter(file_optimizePath(path, pathSyntax), currentPath);
  472. } else {
  473. // Already absolute.
  474. return file_optimizePath(path, pathSyntax);
  475. }
  476. } else {
  477. // Convert from relative path.
  478. return file_optimizePath(file_combinePaths(currentPath, path, pathSyntax), pathSyntax);
  479. }
  480. }
  481. String file_getAbsolutePath(const ReadableString &path) {
  482. return file_getTheoreticalAbsolutePath(path, file_getCurrentPath(), LOCAL_PATH_SYNTAX);
  483. }
  484. int64_t file_getFileSize(const ReadableString& filename) {
  485. int64_t result = -1;
  486. String modifiedFilename = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  487. Buffer buffer;
  488. const NativeChar *nativePath = toNativeString(modifiedFilename, buffer);
  489. #ifdef USE_MICROSOFT_WINDOWS
  490. LARGE_INTEGER fileSize;
  491. HANDLE fileHandle = CreateFileW(nativePath, 0, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  492. if (fileHandle != INVALID_HANDLE_VALUE) {
  493. if (GetFileSizeEx(fileHandle, &fileSize)) {
  494. result = fileSize.QuadPart;
  495. }
  496. CloseHandle(fileHandle);
  497. }
  498. #else
  499. struct stat info;
  500. if (stat(nativePath, &info) == 0) {
  501. result = info.st_size;
  502. }
  503. #endif
  504. return result;
  505. }
  506. String& string_toStreamIndented(String& target, const EntryType& source, const ReadableString& indentation) {
  507. string_append(target, indentation);
  508. if (source == EntryType::NotFound) {
  509. string_append(target, U"not found");
  510. } else if (source == EntryType::File) {
  511. string_append(target, U"a file");
  512. } else if (source == EntryType::Folder) {
  513. string_append(target, U"a folder");
  514. } else if (source == EntryType::SymbolicLink) {
  515. string_append(target, U"a symbolic link");
  516. } else {
  517. string_append(target, U"unhandled");
  518. }
  519. return target;
  520. }
  521. EntryType file_getEntryType(const ReadableString &path) {
  522. EntryType result = EntryType::NotFound;
  523. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  524. Buffer buffer;
  525. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  526. #ifdef USE_MICROSOFT_WINDOWS
  527. DWORD dwAttrib = GetFileAttributesW(nativePath);
  528. if (dwAttrib != INVALID_FILE_ATTRIBUTES) {
  529. if (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) {
  530. result = EntryType::Folder;
  531. } else {
  532. result = EntryType::File;
  533. }
  534. }
  535. #else
  536. struct stat info;
  537. int errorCode = stat(nativePath, &info);
  538. if (errorCode == 0) {
  539. if (S_ISDIR(info.st_mode)) {
  540. result = EntryType::Folder;
  541. } else if (S_ISREG(info.st_mode)) {
  542. result = EntryType::File;
  543. } else if (S_ISLNK(info.st_mode)) {
  544. result = EntryType::SymbolicLink;
  545. } else {
  546. result = EntryType::UnhandledType;
  547. }
  548. }
  549. #endif
  550. return result;
  551. }
  552. bool file_getFolderContent(const ReadableString& folderPath, std::function<void(const ReadableString& entryPath, const ReadableString& entryName, EntryType entryType)> action) {
  553. String optimizedPath = file_optimizePath(folderPath, LOCAL_PATH_SYNTAX);
  554. #ifdef USE_MICROSOFT_WINDOWS
  555. String pattern = file_combinePaths(optimizedPath, U"*.*", LOCAL_PATH_SYNTAX);
  556. Buffer buffer;
  557. const NativeChar *nativePattern = toNativeString(pattern, buffer);
  558. WIN32_FIND_DATAW findData;
  559. HANDLE findHandle = FindFirstFileW(nativePattern, &findData);
  560. if (findHandle == INVALID_HANDLE_VALUE) {
  561. return false;
  562. } else {
  563. while (true) {
  564. String entryName = fromNativeString(findData.cFileName);
  565. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  566. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  567. EntryType entryType = EntryType::UnhandledType;
  568. if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  569. entryType = EntryType::Folder;
  570. } else {
  571. entryType = EntryType::File;
  572. }
  573. action(entryPath, entryName, entryType);
  574. }
  575. if (!FindNextFileW(findHandle, &findData)) { break; }
  576. }
  577. FindClose(findHandle);
  578. }
  579. #else
  580. Buffer buffer;
  581. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  582. DIR *directory = opendir(nativePath);
  583. if (directory == nullptr) {
  584. return false;
  585. } else {
  586. while (true) {
  587. dirent *entry = readdir(directory);
  588. if (entry != nullptr) {
  589. String entryName = fromNativeString(entry->d_name);
  590. if (!string_match(entryName, U".") && !string_match(entryName, U"..")) {
  591. String entryPath = file_combinePaths(optimizedPath, entryName, LOCAL_PATH_SYNTAX);
  592. EntryType entryType = file_getEntryType(entryPath);
  593. action(entryPath, entryName, entryType);
  594. }
  595. } else {
  596. break;
  597. }
  598. }
  599. }
  600. closedir(directory);
  601. #endif
  602. return true;
  603. }
  604. void file_getPathEntries(const ReadableString& path, std::function<void(ReadableString, int64_t, int64_t)> action) {
  605. int64_t sectionStart = 0;
  606. int64_t length = string_length(path);
  607. for (int64_t i = 0; i < string_length(path); i++) {
  608. DsrChar c = path[i];
  609. if (file_isSeparator(c)) {
  610. int64_t sectionEnd = i - 1; // Inclusive end
  611. ReadableString content = string_inclusiveRange(path, sectionStart, sectionEnd);
  612. if (string_length(content)) { action(content, sectionStart, sectionEnd); }
  613. sectionStart = i + 1;
  614. }
  615. }
  616. if (length > sectionStart) {
  617. int64_t sectionEnd = length - 1; // Inclusive end
  618. ReadableString content = string_inclusiveRange(path, sectionStart, sectionEnd);
  619. if (string_length(content)) { action(content, sectionStart, sectionEnd); }
  620. }
  621. }
  622. bool file_createFolder(const ReadableString &path) {
  623. bool result = false;
  624. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  625. Buffer buffer;
  626. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  627. #ifdef USE_MICROSOFT_WINDOWS
  628. // Create folder with permissions inherited.
  629. result = (CreateDirectoryW(nativePath, nullptr) != 0);
  630. #else
  631. // Create folder with default permissions. Read, write and search for owner and group. Read and search for others.
  632. result = (mkdir(nativePath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
  633. #endif
  634. return result;
  635. }
  636. bool file_removeEmptyFolder(const ReadableString& path) {
  637. bool result = false;
  638. String optimizedPath = file_optimizePath(path, LOCAL_PATH_SYNTAX);
  639. Buffer buffer;
  640. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  641. // Remove the empty folder.
  642. #ifdef USE_MICROSOFT_WINDOWS
  643. result = (RemoveDirectoryW(nativePath) != 0);
  644. #else
  645. result = (rmdir(nativePath) == 0);
  646. #endif
  647. return result;
  648. }
  649. bool file_removeFile(const ReadableString& filename) {
  650. bool result = false;
  651. String optimizedPath = file_optimizePath(filename, LOCAL_PATH_SYNTAX);
  652. Buffer buffer;
  653. const NativeChar *nativePath = toNativeString(optimizedPath, buffer);
  654. // Remove the empty folder.
  655. #ifdef USE_MICROSOFT_WINDOWS
  656. result = (DeleteFileW(nativePath) != 0);
  657. #else
  658. result = (unlink(nativePath) == 0);
  659. #endif
  660. return result;
  661. }
  662. // DsrProcess is a reference counted pointer to DsrProcessImpl where the last retrieved status still remains for all to read.
  663. // Because aliasing with multiple users of the same pid would deplete the messages in advance.
  664. struct DsrProcessImpl {
  665. // Once the process has already terminated, process_getStatus will only return lastStatus.
  666. bool terminated = false;
  667. // We can assume that a newly created process is running until we are told that it terminated or crashed,
  668. // because DsrProcessImpl would not be created unless launching the application was successful.
  669. DsrProcessStatus lastStatus = DsrProcessStatus::Running;
  670. #ifdef USE_MICROSOFT_WINDOWS
  671. PROCESS_INFORMATION processInfo;
  672. DsrProcessImpl(const PROCESS_INFORMATION &processInfo)
  673. : processInfo(processInfo) {}
  674. ~DsrProcessImpl() {
  675. CloseHandle(processInfo.hProcess);
  676. CloseHandle(processInfo.hThread);
  677. }
  678. #else
  679. pid_t pid;
  680. DsrProcessImpl(pid_t pid) : pid(pid) {}
  681. #endif
  682. };
  683. DsrProcessStatus process_getStatus(const DsrProcess &process) {
  684. if (process.isNull()) {
  685. return DsrProcessStatus::NotStarted;
  686. } else {
  687. if (!process->terminated) {
  688. #ifdef USE_MICROSOFT_WINDOWS
  689. DWORD status = WaitForSingleObject(process->processInfo.hProcess, 0);
  690. if (status == WAIT_OBJECT_0) {
  691. DWORD processResult;
  692. GetExitCodeProcess(process->processInfo.hProcess, &processResult);
  693. process->lastStatus = (processResult == 0) ? DsrProcessStatus::Completed : DsrProcessStatus::Crashed;
  694. process->terminated = true;
  695. }
  696. #else
  697. // When using WNOHANG, waitpid returns zero when the program is still running, and the child pid if it terminated.
  698. int status = 0;
  699. if (waitpid(process->pid, &status, WNOHANG) != 0) {
  700. if (WIFEXITED(status)) {
  701. if (WEXITSTATUS(status) == 0) {
  702. // The program finished and returned 0 for success.
  703. process->lastStatus = DsrProcessStatus::Completed;
  704. } else {
  705. // The program finished, but returned a non-zero result indicating that something still went wrong.
  706. process->lastStatus = DsrProcessStatus::Crashed;
  707. }
  708. process->terminated = true;
  709. } else if (WIFSIGNALED(status)) {
  710. // The program was stopped due to a hard crash.
  711. process->lastStatus = DsrProcessStatus::Crashed;
  712. process->terminated = true;
  713. }
  714. }
  715. #endif
  716. }
  717. return process->lastStatus;
  718. }
  719. }
  720. DsrProcess process_execute(const ReadableString& programPath, List<String> arguments, bool mustWork) {
  721. // Convert the program path into the native format.
  722. String optimizedPath = file_optimizePath(programPath, LOCAL_PATH_SYNTAX);
  723. // Convert
  724. #ifdef USE_MICROSOFT_WINDOWS
  725. DsrChar separator = U' ';
  726. #else
  727. DsrChar separator = U'\0';
  728. #endif
  729. String flattenedArguments;
  730. string_append(flattenedArguments, optimizedPath);
  731. string_appendChar(flattenedArguments, separator);
  732. for (int64_t a = 0; a < arguments.length(); a++) {
  733. string_append(flattenedArguments, arguments[a]);
  734. string_appendChar(flattenedArguments, separator);
  735. }
  736. Buffer argBuffer;
  737. const NativeChar *nativeArgs = toNativeString(flattenedArguments, argBuffer);
  738. #ifdef USE_MICROSOFT_WINDOWS
  739. STARTUPINFOW startInfo;
  740. PROCESS_INFORMATION processInfo;
  741. memset(&startInfo, 0, sizeof(STARTUPINFO));
  742. memset(&processInfo, 0, sizeof(PROCESS_INFORMATION));
  743. startInfo.cb = sizeof(STARTUPINFO);
  744. if (CreateProcessW(nullptr, (LPWSTR)nativeArgs, nullptr, nullptr, true, 0, nullptr, nullptr, &startInfo, &processInfo)) {
  745. return handle_create<DsrProcessImpl>(processInfo).setName("DSR Process"); // Success
  746. } else {
  747. if (mustWork) {
  748. throwError(U"Failed to call ", programPath, U"! False returned from CreateProcessW.\n");
  749. }
  750. return DsrProcess(); // Failure
  751. }
  752. #else
  753. Buffer pathBuffer;
  754. const NativeChar *nativePath = toNativeString(optimizedPath, pathBuffer);
  755. int64_t codePoints = buffer_getSize(argBuffer) / sizeof(NativeChar);
  756. // Count arguments.
  757. int argc = arguments.length() + 1;
  758. // Allocate an array of pointers for each argument and a null terminator.
  759. VirtualStackAllocation<const NativeChar *> argv(argc + 1);
  760. // Fill the array with pointers to the native strings.
  761. int64_t startOffset = 0;
  762. int currentArg = 0;
  763. for (int64_t c = 0; c < codePoints && currentArg < argc; c++) {
  764. if (nativeArgs[c] == 0) {
  765. argv[currentArg] = &(nativeArgs[startOffset]);
  766. startOffset = c + 1;
  767. currentArg++;
  768. }
  769. }
  770. argv[currentArg] = nullptr;
  771. pid_t pid = 0;
  772. int error = posix_spawn(&pid, nativePath, nullptr, nullptr, (char**)argv.getUnsafe(), environ);
  773. if (error == 0) {
  774. return handle_create<DsrProcessImpl>(pid).setName("DSR Process"); // Success
  775. } else {
  776. if (mustWork) {
  777. throwError(U"Failed to call ", programPath, U"! Got error code ", error, " from posix_spawn.\n");
  778. }
  779. return DsrProcess(); // Failure
  780. }
  781. #endif
  782. }
  783. }