Debian Codegraph @

third-party/xxhash/cli/xsum_os_specific.c

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