util.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #ifndef UTIL_H_MODULE
  11. #define UTIL_H_MODULE
  12. /*-****************************************
  13. * Dependencies
  14. ******************************************/
  15. #include "platform.h" /* PLATFORM_POSIX_VERSION, ZSTD_NANOSLEEP_SUPPORT, ZSTD_SETPRIORITY_SUPPORT */
  16. #include <stddef.h> /* size_t, ptrdiff_t */
  17. #include <stdio.h> /* FILE */
  18. #include <sys/types.h> /* stat, utime */
  19. #include <sys/stat.h> /* stat, chmod */
  20. #include "../lib/common/mem.h" /* U64 */
  21. #if !(defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__))
  22. #include <libgen.h>
  23. #endif
  24. /*-************************************************************
  25. * Fix fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW
  26. ***************************************************************/
  27. #if defined(LIBC_NO_FSEEKO)
  28. /* Some older libc implementations don't include these functions (e.g. Bionic < 24) */
  29. # define UTIL_fseek fseek
  30. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  31. # define UTIL_fseek _fseeki64
  32. #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */
  33. # define UTIL_fseek fseeko
  34. #elif defined(__MINGW32__) && defined(__MSVCRT__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS)
  35. # define UTIL_fseek fseeko64
  36. #else
  37. # define UTIL_fseek fseek
  38. #endif
  39. /*-*************************************************
  40. * Sleep & priority functions: Windows - Posix - others
  41. ***************************************************/
  42. #if defined(_WIN32)
  43. # include <windows.h>
  44. # define SET_REALTIME_PRIORITY SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS)
  45. # define UTIL_sleep(s) Sleep(1000*s)
  46. # define UTIL_sleepMilli(milli) Sleep(milli)
  47. #elif PLATFORM_POSIX_VERSION > 0 /* Unix-like operating system */
  48. # include <unistd.h> /* sleep */
  49. # define UTIL_sleep(s) sleep(s)
  50. # if ZSTD_NANOSLEEP_SUPPORT /* necessarily defined in platform.h */
  51. # define UTIL_sleepMilli(milli) { struct timespec t; t.tv_sec=0; t.tv_nsec=milli*1000000ULL; nanosleep(&t, NULL); }
  52. # else
  53. # define UTIL_sleepMilli(milli) /* disabled */
  54. # endif
  55. # if ZSTD_SETPRIORITY_SUPPORT
  56. # include <sys/resource.h> /* setpriority */
  57. # define SET_REALTIME_PRIORITY setpriority(PRIO_PROCESS, 0, -20)
  58. # else
  59. # define SET_REALTIME_PRIORITY /* disabled */
  60. # endif
  61. #else /* unknown non-unix operating system */
  62. # define UTIL_sleep(s) /* disabled */
  63. # define UTIL_sleepMilli(milli) /* disabled */
  64. # define SET_REALTIME_PRIORITY /* disabled */
  65. #endif
  66. /*-****************************************
  67. * Compiler specifics
  68. ******************************************/
  69. #if defined(__INTEL_COMPILER)
  70. # pragma warning(disable : 177) /* disable: message #177: function was declared but never referenced, useful with UTIL_STATIC */
  71. #endif
  72. #if defined(__GNUC__)
  73. # define UTIL_STATIC static __attribute__((unused))
  74. #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  75. # define UTIL_STATIC static inline
  76. #elif defined(_MSC_VER)
  77. # define UTIL_STATIC static __inline
  78. #else
  79. # define UTIL_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
  80. #endif
  81. #if defined (__cplusplus)
  82. extern "C" {
  83. #endif
  84. /*-****************************************
  85. * Console log
  86. ******************************************/
  87. extern int g_utilDisplayLevel;
  88. /**
  89. * Displays a message prompt and returns success (0) if first character from stdin
  90. * matches any from acceptableLetters. Otherwise, returns failure (1) and displays abortMsg.
  91. * If any of the inputs are stdin itself, then automatically return failure (1).
  92. */
  93. int UTIL_requireUserConfirmation(const char* prompt, const char* abortMsg, const char* acceptableLetters, int hasStdinInput);
  94. /*-****************************************
  95. * File functions
  96. ******************************************/
  97. #if defined(_MSC_VER)
  98. typedef struct __stat64 stat_t;
  99. typedef int mode_t;
  100. #elif defined(__MINGW32__) && defined (__MSVCRT__)
  101. typedef struct _stati64 stat_t;
  102. #else
  103. typedef struct stat stat_t;
  104. #endif
  105. #if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__) /* windows support */
  106. #define PATH_SEP '\\'
  107. #define STRDUP(s) _strdup(s)
  108. #else
  109. #define PATH_SEP '/'
  110. #define STRDUP(s) strdup(s)
  111. #endif
  112. /**
  113. * Calls platform's equivalent of stat() on filename and writes info to statbuf.
  114. * Returns success (1) or failure (0).
  115. *
  116. * UTIL_fstat() is like UTIL_stat() but takes an optional fd that refers to the
  117. * file in question. It turns out that this can be meaningfully faster. If fd is
  118. * -1, behaves just like UTIL_stat() (i.e., falls back to using the filename).
  119. */
  120. int UTIL_stat(const char* filename, stat_t* statbuf);
  121. int UTIL_fstat(const int fd, const char* filename, stat_t* statbuf);
  122. /**
  123. * Instead of getting a file's stats, this updates them with the info in the
  124. * provided stat_t. Currently sets owner, group, atime, and mtime. Will only
  125. * update this info for regular files.
  126. *
  127. * UTIL_setFDStat() also takes an fd, and will preferentially use that to
  128. * indicate which file to modify, If fd is -1, it will fall back to using the
  129. * filename.
  130. */
  131. int UTIL_setFileStat(const char* filename, const stat_t* statbuf);
  132. int UTIL_setFDStat(const int fd, const char* filename, const stat_t* statbuf);
  133. /**
  134. * Set atime to now and mtime to the st_mtim in statbuf.
  135. *
  136. * Directly wraps utime() or utimensat(). Returns -1 on error.
  137. * Does not validate filename is valid.
  138. */
  139. int UTIL_utime(const char* filename, const stat_t *statbuf);
  140. /*
  141. * These helpers operate on a pre-populated stat_t, i.e., the result of
  142. * calling one of the above functions.
  143. */
  144. int UTIL_isRegularFileStat(const stat_t* statbuf);
  145. int UTIL_isDirectoryStat(const stat_t* statbuf);
  146. int UTIL_isFIFOStat(const stat_t* statbuf);
  147. int UTIL_isBlockDevStat(const stat_t* statbuf);
  148. U64 UTIL_getFileSizeStat(const stat_t* statbuf);
  149. /**
  150. * Like chmod(), but only modifies regular files. Provided statbuf may be NULL,
  151. * in which case this function will stat() the file internally, in order to
  152. * check whether it should be modified.
  153. *
  154. * If fd is -1, fd is ignored and the filename is used.
  155. */
  156. int UTIL_chmod(char const* filename, const stat_t* statbuf, mode_t permissions);
  157. int UTIL_fchmod(const int fd, char const* filename, const stat_t* statbuf, mode_t permissions);
  158. /*
  159. * In the absence of a pre-existing stat result on the file in question, these
  160. * functions will do a stat() call internally and then use that result to
  161. * compute the needed information.
  162. */
  163. int UTIL_isRegularFile(const char* infilename);
  164. int UTIL_isDirectory(const char* infilename);
  165. int UTIL_isSameFile(const char* file1, const char* file2);
  166. int UTIL_isSameFileStat(const char* file1, const char* file2, const stat_t* file1Stat, const stat_t* file2Stat);
  167. int UTIL_isCompressedFile(const char* infilename, const char *extensionList[]);
  168. int UTIL_isLink(const char* infilename);
  169. int UTIL_isFIFO(const char* infilename);
  170. /**
  171. * Returns with the given file descriptor is a console.
  172. * Allows faking whether stdin/stdout/stderr is a console
  173. * using UTIL_fake*IsConsole().
  174. */
  175. int UTIL_isConsole(FILE* file);
  176. /**
  177. * Pretends that stdin/stdout/stderr is a console for testing.
  178. */
  179. void UTIL_fakeStdinIsConsole(void);
  180. void UTIL_fakeStdoutIsConsole(void);
  181. void UTIL_fakeStderrIsConsole(void);
  182. /**
  183. * Emit traces for functions that read, or modify file metadata.
  184. */
  185. void UTIL_traceFileStat(void);
  186. #define UTIL_FILESIZE_UNKNOWN ((U64)(-1))
  187. U64 UTIL_getFileSize(const char* infilename);
  188. U64 UTIL_getTotalFileSize(const char* const * fileNamesTable, unsigned nbFiles);
  189. /**
  190. * Take @size in bytes,
  191. * prepare the components to pretty-print it in a scaled way.
  192. * The components in the returned struct should be passed in
  193. * precision, value, suffix order to a "%.*f%s" format string.
  194. * Output policy is sensible to @g_utilDisplayLevel,
  195. * for verbose mode (@g_utilDisplayLevel >= 4),
  196. * does not scale down.
  197. */
  198. typedef struct {
  199. double value;
  200. int precision;
  201. const char* suffix;
  202. } UTIL_HumanReadableSize_t;
  203. UTIL_HumanReadableSize_t UTIL_makeHumanReadableSize(U64 size);
  204. int UTIL_compareStr(const void *p1, const void *p2);
  205. const char* UTIL_getFileExtension(const char* infilename);
  206. void UTIL_mirrorSourceFilesDirectories(const char** fileNamesTable, unsigned int nbFiles, const char *outDirName);
  207. char* UTIL_createMirroredDestDirName(const char* srcFileName, const char* outDirRootName);
  208. /*-****************************************
  209. * Lists of Filenames
  210. ******************************************/
  211. typedef struct
  212. { const char** fileNames;
  213. char* buf; /* fileNames are stored in this buffer (or are read-only) */
  214. size_t tableSize; /* nb of fileNames */
  215. size_t tableCapacity;
  216. } FileNamesTable;
  217. /*! UTIL_createFileNamesTable_fromFileName() :
  218. * read filenames from @inputFileName, and store them into returned object.
  219. * @return : a FileNamesTable*, or NULL in case of error (ex: @inputFileName doesn't exist).
  220. * Note: inputFileSize must be less than 50MB
  221. */
  222. FileNamesTable*
  223. UTIL_createFileNamesTable_fromFileName(const char* inputFileName);
  224. /*! UTIL_assembleFileNamesTable() :
  225. * This function takes ownership of its arguments, @filenames and @buf,
  226. * and store them inside the created object.
  227. * note : this function never fails,
  228. * it will rather exit() the program if internal allocation fails.
  229. * @return : resulting FileNamesTable* object.
  230. */
  231. FileNamesTable*
  232. UTIL_assembleFileNamesTable(const char** filenames, size_t tableSize, char* buf);
  233. /*! UTIL_freeFileNamesTable() :
  234. * This function is compatible with NULL argument and never fails.
  235. */
  236. void UTIL_freeFileNamesTable(FileNamesTable* table);
  237. /*! UTIL_mergeFileNamesTable():
  238. * @return : FileNamesTable*, concatenation of @table1 and @table2
  239. * note: @table1 and @table2 are consumed (freed) by this operation
  240. */
  241. FileNamesTable*
  242. UTIL_mergeFileNamesTable(FileNamesTable* table1, FileNamesTable* table2);
  243. /*! UTIL_expandFNT() :
  244. * read names from @fnt, and expand those corresponding to directories
  245. * update @fnt, now containing only file names,
  246. * note : in case of error, @fnt[0] is NULL
  247. */
  248. void UTIL_expandFNT(FileNamesTable** fnt, int followLinks);
  249. /*! UTIL_createFNT_fromROTable() :
  250. * copy the @filenames pointer table inside the returned object.
  251. * The names themselves are still stored in their original buffer, which must outlive the object.
  252. * @return : a FileNamesTable* object,
  253. * or NULL in case of error
  254. */
  255. FileNamesTable*
  256. UTIL_createFNT_fromROTable(const char** filenames, size_t nbFilenames);
  257. /*! UTIL_allocateFileNamesTable() :
  258. * Allocates a table of const char*, to insert read-only names later on.
  259. * The created FileNamesTable* doesn't hold a buffer.
  260. * @return : FileNamesTable*, or NULL, if allocation fails.
  261. */
  262. FileNamesTable* UTIL_allocateFileNamesTable(size_t tableSize);
  263. /*! UTIL_searchFileNamesTable() :
  264. * Searched through entries in FileNamesTable for a specific name.
  265. * @return : index of entry if found or -1 if not found
  266. */
  267. int UTIL_searchFileNamesTable(FileNamesTable* table, char const* name);
  268. /*! UTIL_refFilename() :
  269. * Add a reference to read-only name into @fnt table.
  270. * As @filename is only referenced, its lifetime must outlive @fnt.
  271. * Internal table must be large enough to reference a new member,
  272. * otherwise its UB (protected by an `assert()`).
  273. */
  274. void UTIL_refFilename(FileNamesTable* fnt, const char* filename);
  275. /* UTIL_createExpandedFNT() is only active if UTIL_HAS_CREATEFILELIST is defined.
  276. * Otherwise, UTIL_createExpandedFNT() is a shell function which does nothing
  277. * apart from displaying a warning message.
  278. */
  279. #ifdef _WIN32
  280. # define UTIL_HAS_CREATEFILELIST
  281. #elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */
  282. # define UTIL_HAS_CREATEFILELIST
  283. # define UTIL_HAS_MIRRORFILELIST
  284. #else
  285. /* do not define UTIL_HAS_CREATEFILELIST */
  286. #endif
  287. /*! UTIL_createExpandedFNT() :
  288. * read names from @filenames, and expand those corresponding to directories.
  289. * links are followed or not depending on @followLinks directive.
  290. * @return : an expanded FileNamesTable*, where each name is a file
  291. * or NULL in case of error
  292. */
  293. FileNamesTable*
  294. UTIL_createExpandedFNT(const char* const* filenames, size_t nbFilenames, int followLinks);
  295. #if defined(_WIN32)
  296. DWORD CountSetBits(ULONG_PTR bitMask);
  297. #endif
  298. /*-****************************************
  299. * System
  300. ******************************************/
  301. int UTIL_countCores(int logical);
  302. int UTIL_countPhysicalCores(void);
  303. int UTIL_countLogicalCores(void);
  304. #if defined (__cplusplus)
  305. }
  306. #endif
  307. #endif /* UTIL_H_MODULE */