xsum_os_specific.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * xxhsum - Command line interface for xxhash algorithms
  3. * Copyright (C) 2013-2020 Yann Collet
  4. *
  5. * GPL v2 License
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License along
  18. * with this program; if not, write to the Free Software Foundation, Inc.,
  19. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * You can contact the author at:
  22. * - xxHash homepage: https://www.xxhash.com
  23. * - xxHash source repository: https://github.com/Cyan4973/xxHash
  24. */
  25. #include "xsum_config.h"
  26. #include "xsum_os_specific.h"
  27. #include <stdio.h>
  28. #include <stdarg.h>
  29. #include <stdlib.h>
  30. #include <sys/types.h> /* struct stat / __wstat64 */
  31. #include <sys/stat.h> /* stat() / _stat64() */
  32. /*
  33. * This file contains all of the ugly boilerplate to make xxhsum work across
  34. * platforms.
  35. */
  36. #if defined(_MSC_VER) || XSUM_WIN32_USE_WCHAR
  37. typedef struct __stat64 XSUM_stat_t;
  38. # if defined(_MSC_VER)
  39. typedef int mode_t;
  40. # endif
  41. #else
  42. typedef struct stat XSUM_stat_t;
  43. #endif
  44. #if (defined(__linux__) && (XSUM_PLATFORM_POSIX_VERSION >= 1)) \
  45. || (XSUM_PLATFORM_POSIX_VERSION >= 200112L) \
  46. || defined(__DJGPP__) \
  47. || defined(__MSYS__)
  48. # include <unistd.h> /* isatty */
  49. # define XSUM_IS_CONSOLE(stdStream) isatty(fileno(stdStream))
  50. #elif defined(MSDOS) || defined(OS2)
  51. # include <io.h> /* _isatty */
  52. # define XSUM_IS_CONSOLE(stdStream) _isatty(_fileno(stdStream))
  53. #elif defined(WIN32) || defined(_WIN32)
  54. # include <io.h> /* _isatty */
  55. # include <windows.h> /* DeviceIoControl, HANDLE, FSCTL_SET_SPARSE */
  56. # include <stdio.h> /* FILE */
  57. static __inline int XSUM_IS_CONSOLE(FILE* stdStream)
  58. {
  59. DWORD dummy;
  60. return _isatty(_fileno(stdStream)) && GetConsoleMode((HANDLE)_get_osfhandle(_fileno(stdStream)), &dummy);
  61. }
  62. #else
  63. # define XSUM_IS_CONSOLE(stdStream) 0
  64. #endif
  65. #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(_WIN32)
  66. # include <fcntl.h> /* _O_BINARY */
  67. # include <io.h> /* _setmode, _fileno, _get_osfhandle */
  68. # if !defined(__DJGPP__)
  69. # include <windows.h> /* DeviceIoControl, HANDLE, FSCTL_SET_SPARSE */
  70. # include <winioctl.h> /* FSCTL_SET_SPARSE */
  71. # define XSUM_SET_BINARY_MODE(file) { int const unused=_setmode(_fileno(file), _O_BINARY); (void)unused; }
  72. # else
  73. # define XSUM_SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
  74. # endif
  75. #else
  76. # define XSUM_SET_BINARY_MODE(file) ((void)file)
  77. #endif
  78. XSUM_API int XSUM_isConsole(FILE* stream)
  79. {
  80. return XSUM_IS_CONSOLE(stream);
  81. }
  82. XSUM_API void XSUM_setBinaryMode(FILE* stream)
  83. {
  84. XSUM_SET_BINARY_MODE(stream);
  85. }
  86. #if !XSUM_WIN32_USE_WCHAR
  87. XSUM_API FILE* XSUM_fopen(const char* filename, const char* mode)
  88. {
  89. return fopen(filename, mode);
  90. }
  91. XSUM_ATTRIBUTE((__format__(__printf__, 2, 0)))
  92. XSUM_API int XSUM_vfprintf(FILE* stream, const char* format, va_list ap)
  93. {
  94. return vfprintf(stream, format, ap);
  95. }
  96. static int XSUM_stat(const char* infilename, XSUM_stat_t* statbuf)
  97. {
  98. #if defined(_MSC_VER)
  99. return _stat64(infilename, statbuf);
  100. #else
  101. return stat(infilename, statbuf);
  102. #endif
  103. }
  104. #ifndef XSUM_NO_MAIN
  105. int main(int argc, char* argv[])
  106. {
  107. return XSUM_main(argc, argv);
  108. }
  109. #endif
  110. /* Unicode helpers for Windows to make UTF-8 act as it should. */
  111. #else
  112. # include <windows.h>
  113. # include <wchar.h>
  114. /*****************************************************************************
  115. * Unicode conversion tools
  116. *****************************************************************************/
  117. /*
  118. * Converts a UTF-8 string to UTF-16. Acts like strdup. The string must be freed afterwards.
  119. * This version allows keeping the output length.
  120. */
  121. static wchar_t* XSUM_widenString(const char* str, int* lenOut)
  122. {
  123. int const len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  124. if (lenOut != NULL) *lenOut = len;
  125. if (len == 0) return NULL;
  126. { wchar_t* buf = (wchar_t*)malloc((size_t)len * sizeof(wchar_t));
  127. if (buf != NULL) {
  128. if (MultiByteToWideChar(CP_UTF8, 0, str, -1, buf, len) == 0) {
  129. free(buf);
  130. return NULL;
  131. } }
  132. return buf;
  133. }
  134. }
  135. /*
  136. * Converts a UTF-16 string to UTF-8. Acts like strdup. The string must be freed afterwards.
  137. * This version allows keeping the output length.
  138. */
  139. static char* XSUM_narrowString(const wchar_t *str, int *lenOut)
  140. {
  141. int len = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
  142. if (lenOut != NULL) *lenOut = len;
  143. if (len == 0) return NULL;
  144. { char* const buf = (char*)malloc((size_t)len * sizeof(char));
  145. if (buf != NULL) {
  146. if (WideCharToMultiByte(CP_UTF8, 0, str, -1, buf, len, NULL, NULL) == 0) {
  147. free(buf);
  148. return NULL;
  149. } }
  150. return buf;
  151. }
  152. }
  153. /*****************************************************************************
  154. * File helpers
  155. *****************************************************************************/
  156. /*
  157. * fopen wrapper that supports UTF-8
  158. *
  159. * fopen will only accept ANSI filenames, which means that we can't open Unicode filenames.
  160. *
  161. * In order to open a Unicode filename, we need to convert filenames to UTF-16 and use _wfopen.
  162. */
  163. XSUM_API FILE* XSUM_fopen(const char* filename, const char* mode)
  164. {
  165. FILE* f = NULL;
  166. wchar_t* const wide_filename = XSUM_widenString(filename, NULL);
  167. if (wide_filename != NULL) {
  168. wchar_t* const wide_mode = XSUM_widenString(mode, NULL);
  169. if (wide_mode != NULL) {
  170. f = _wfopen(wide_filename, wide_mode);
  171. free(wide_mode);
  172. }
  173. free(wide_filename);
  174. }
  175. return f;
  176. }
  177. /*
  178. * stat() wrapper which supports UTF-8 filenames.
  179. */
  180. static int XSUM_stat(const char* infilename, XSUM_stat_t* statbuf)
  181. {
  182. int r = -1;
  183. wchar_t* const wide_filename = XSUM_widenString(infilename, NULL);
  184. if (wide_filename != NULL) {
  185. r = _wstat64(wide_filename, statbuf);
  186. free(wide_filename);
  187. }
  188. return r;
  189. }
  190. /*
  191. * In case it isn't available, this is what MSVC 2019 defines in stdarg.h.
  192. */
  193. #if defined(_MSC_VER) && !defined(__clang__) && !defined(va_copy)
  194. # define XSUM_va_copy(destination, source) ((destination) = (source))
  195. #else
  196. # define XSUM_va_copy(destination, source) va_copy(destination, source)
  197. #endif
  198. /*
  199. * vasprintf for Windows.
  200. */
  201. XSUM_ATTRIBUTE((__format__(__printf__, 2, 0)))
  202. static int XSUM_vasprintf(char** strp, const char* format, va_list ap)
  203. {
  204. int ret;
  205. int size;
  206. va_list copy;
  207. /*
  208. * To be safe, make a va_copy.
  209. *
  210. * Note that Microsoft doesn't use va_copy in its sample code:
  211. * https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/vsprintf-vsprintf-l-vswprintf-vswprintf-l-vswprintf-l?view=vs-2019
  212. */
  213. XSUM_va_copy(copy, ap);
  214. /* Calculate how many characters we need */
  215. size = _vscprintf(format, ap);
  216. va_end(copy);
  217. if (size < 0) {
  218. *strp = NULL;
  219. return size;
  220. } else {
  221. *strp = (char*) malloc((size_t)size + 1);
  222. if (*strp == NULL) {
  223. return -1;
  224. }
  225. /* vsprintf into the new buffer */
  226. ret = vsprintf(*strp, format, ap);
  227. if (ret < 0) {
  228. free(*strp);
  229. *strp = NULL;
  230. }
  231. return ret;
  232. }
  233. }
  234. /*
  235. * fprintf wrapper that supports UTF-8.
  236. *
  237. * fprintf doesn't properly handle Unicode on Windows.
  238. *
  239. * Additionally, it is codepage sensitive on console and may crash the program.
  240. *
  241. * Instead, we use vsnprintf, and either print with fwrite or convert to UTF-16
  242. * for console output and use the codepage-independent WriteConsoleW.
  243. *
  244. * Credit to t-mat: https://github.com/t-mat/xxHash/commit/5691423
  245. */
  246. XSUM_ATTRIBUTE((__format__(__printf__, 2, 0)))
  247. XSUM_API int XSUM_vfprintf(FILE *stream, const char *format, va_list ap)
  248. {
  249. int result;
  250. char* u8_str = NULL;
  251. /*
  252. * Generate the UTF-8 output string with vasprintf.
  253. */
  254. result = XSUM_vasprintf(&u8_str, format, ap);
  255. if (result >= 0) {
  256. const size_t nchar = (size_t)result + 1;
  257. /*
  258. * Check if we are outputting to a console. Don't use XSUM_isConsole
  259. * directly -- we don't need to call _get_osfhandle twice.
  260. */
  261. int fileNb = _fileno(stream);
  262. intptr_t handle_raw = _get_osfhandle(fileNb);
  263. HANDLE handle = (HANDLE)handle_raw;
  264. DWORD dwTemp;
  265. if (handle_raw < 0) {
  266. result = -1;
  267. } else if (_isatty(fileNb) && GetConsoleMode(handle, &dwTemp)) {
  268. /*
  269. * Convert to UTF-16 and output with WriteConsoleW.
  270. *
  271. * This is codepage independent and works on Windows XP's default
  272. * msvcrt.dll.
  273. */
  274. int len;
  275. wchar_t* const u16_buf = XSUM_widenString(u8_str, &len);
  276. if (u16_buf == NULL) {
  277. result = -1;
  278. } else {
  279. if (WriteConsoleW(handle, u16_buf, (DWORD)len - 1, &dwTemp, NULL)) {
  280. result = (int)dwTemp;
  281. } else {
  282. result = -1;
  283. }
  284. free(u16_buf);
  285. }
  286. } else {
  287. /* fwrite the UTF-8 string if we are printing to a file */
  288. result = (int)fwrite(u8_str, 1, nchar - 1, stream);
  289. if (result == 0) {
  290. result = -1;
  291. }
  292. }
  293. free(u8_str);
  294. }
  295. return result;
  296. }
  297. #ifndef XSUM_NO_MAIN
  298. /*****************************************************************************
  299. * Command Line argument parsing
  300. *****************************************************************************/
  301. /* Converts a UTF-16 argv to UTF-8. */
  302. static char** XSUM_convertArgv(int argc, wchar_t* utf16_argv[])
  303. {
  304. char** const utf8_argv = (char**)malloc((size_t)(argc + 1) * sizeof(char*));
  305. if (utf8_argv != NULL) {
  306. int i;
  307. for (i = 0; i < argc; i++) {
  308. utf8_argv[i] = XSUM_narrowString(utf16_argv[i], NULL);
  309. if (utf8_argv[i] == NULL) {
  310. /* Out of memory, whoops. */
  311. while (i-- > 0) {
  312. free(utf8_argv[i]);
  313. }
  314. free(utf8_argv);
  315. return NULL;
  316. }
  317. }
  318. utf8_argv[argc] = NULL;
  319. }
  320. return utf8_argv;
  321. }
  322. /* Frees arguments returned by XSUM_convertArgv */
  323. static void XSUM_freeArgv(int argc, char** argv)
  324. {
  325. int i;
  326. if (argv == NULL) {
  327. return;
  328. }
  329. for (i = 0; i < argc; i++) {
  330. free(argv[i]);
  331. }
  332. free(argv);
  333. }
  334. static int XSUM_wmain(int argc, wchar_t* utf16_argv[])
  335. {
  336. /* Convert the UTF-16 arguments to UTF-8. */
  337. char** utf8_argv = XSUM_convertArgv(argc, utf16_argv);
  338. if (utf8_argv == NULL) {
  339. /* An unfortunate but incredibly unlikely error. */
  340. fprintf(stderr, "xxhsum: error converting command line arguments!\n");
  341. abort();
  342. } else {
  343. int ret;
  344. /*
  345. * MinGW's terminal uses full block buffering for stderr.
  346. *
  347. * This is nonstandard behavior and causes text to not display until
  348. * the buffer fills.
  349. *
  350. * `setvbuf()` can easily correct this to make text display instantly.
  351. */
  352. setvbuf(stderr, NULL, _IONBF, 0);
  353. /* Call our real main function */
  354. ret = XSUM_main(argc, utf8_argv);
  355. /* Cleanup */
  356. XSUM_freeArgv(argc, utf8_argv);
  357. return ret;
  358. }
  359. }
  360. #if XSUM_WIN32_USE_WMAIN
  361. /*
  362. * The preferred method of obtaining the real UTF-16 arguments. Always works
  363. * on MSVC, sometimes works on MinGW-w64 depending on the compiler flags.
  364. */
  365. #ifdef __cplusplus
  366. extern "C"
  367. #endif
  368. int __cdecl wmain(int argc, wchar_t* utf16_argv[])
  369. {
  370. return XSUM_wmain(argc, utf16_argv);
  371. }
  372. #else /* !XSUM_WIN32_USE_WMAIN */
  373. /*
  374. * Wrap `XSUM_wmain()` using `main()` and `__wgetmainargs()` on MinGW without
  375. * Unicode support.
  376. *
  377. * `__wgetmainargs()` is used in the CRT startup to retrieve the arguments for
  378. * `wmain()`, so we use it on MinGW to emulate `wmain()`.
  379. *
  380. * It is an internal function and not declared in any public headers, so we
  381. * have to declare it manually.
  382. *
  383. * An alternative that doesn't mess with internal APIs is `GetCommandLineW()`
  384. * with `CommandLineToArgvW()`, but the former doesn't expand wildcards and the
  385. * latter requires linking to Shell32.dll and its numerous dependencies.
  386. *
  387. * This method keeps our dependencies to kernel32.dll and the CRT.
  388. *
  389. * https://docs.microsoft.com/en-us/cpp/c-runtime-library/getmainargs-wgetmainargs?view=vs-2019
  390. */
  391. typedef struct {
  392. int newmode;
  393. } _startupinfo;
  394. #ifdef __cplusplus
  395. extern "C"
  396. #endif
  397. int __cdecl __wgetmainargs(
  398. int* Argc,
  399. wchar_t*** Argv,
  400. wchar_t*** Env,
  401. int DoWildCard,
  402. _startupinfo* StartInfo
  403. );
  404. int main(int ansi_argc, char* ansi_argv[])
  405. {
  406. int utf16_argc;
  407. wchar_t** utf16_argv;
  408. wchar_t** utf16_envp; /* Unused but required */
  409. _startupinfo startinfo = {0}; /* 0 == don't change new mode */
  410. /* Get wmain's UTF-16 arguments. Make sure we expand wildcards. */
  411. if (__wgetmainargs(&utf16_argc, &utf16_argv, &utf16_envp, 1, &startinfo) < 0)
  412. /* In the very unlikely case of an error, use the ANSI arguments. */
  413. return XSUM_main(ansi_argc, ansi_argv);
  414. /* Call XSUM_wmain with our UTF-16 arguments */
  415. return XSUM_wmain(utf16_argc, utf16_argv);
  416. }
  417. #endif /* !XSUM_WIN32_USE_WMAIN */
  418. #endif /* !XSUM_NO_MAIN */
  419. #endif /* XSUM_WIN32_USE_WCHAR */
  420. /*
  421. * Determines whether the file at filename is a directory.
  422. */
  423. XSUM_API int XSUM_isDirectory(const char* filename)
  424. {
  425. XSUM_stat_t statbuf;
  426. int r = XSUM_stat(filename, &statbuf);
  427. #ifdef _MSC_VER
  428. if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
  429. #else
  430. if (!r && S_ISDIR(statbuf.st_mode)) return 1;
  431. #endif
  432. return 0;
  433. }
  434. /*
  435. * Returns the filesize of the file at filename.
  436. */
  437. XSUM_API XSUM_U64 XSUM_getFileSize(const char* filename)
  438. {
  439. XSUM_stat_t statbuf;
  440. int r = XSUM_stat(filename, &statbuf);
  441. if (r || !S_ISREG(statbuf.st_mode)) return 0; /* No good... */
  442. return (XSUM_U64)statbuf.st_size;
  443. }