util.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640
  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. #if defined (__cplusplus)
  11. extern "C" {
  12. #endif
  13. /*-****************************************
  14. * Dependencies
  15. ******************************************/
  16. #include "util.h" /* note : ensure that platform.h is included first ! */
  17. #include <stdlib.h> /* malloc, realloc, free */
  18. #include <stdio.h> /* fprintf */
  19. #include <time.h> /* clock_t, clock, CLOCKS_PER_SEC, nanosleep */
  20. #include <errno.h>
  21. #include <assert.h>
  22. #if defined(_WIN32)
  23. # include <sys/utime.h> /* utime */
  24. # include <io.h> /* _chmod */
  25. #else
  26. # include <unistd.h> /* chown, stat */
  27. # if PLATFORM_POSIX_VERSION < 200809L || !defined(st_mtime)
  28. # include <utime.h> /* utime */
  29. # else
  30. # include <fcntl.h> /* AT_FDCWD */
  31. # include <sys/stat.h> /* utimensat */
  32. # endif
  33. #endif
  34. #if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__)
  35. #include <direct.h> /* needed for _mkdir in windows */
  36. #endif
  37. #if defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */
  38. # include <dirent.h> /* opendir, readdir */
  39. # include <string.h> /* strerror, memcpy */
  40. #endif /* #ifdef _WIN32 */
  41. /*-****************************************
  42. * Internal Macros
  43. ******************************************/
  44. /* CONTROL is almost like an assert(), but is never disabled.
  45. * It's designed for failures that may happen rarely,
  46. * but we don't want to maintain a specific error code path for them,
  47. * such as a malloc() returning NULL for example.
  48. * Since it's always active, this macro can trigger side effects.
  49. */
  50. #define CONTROL(c) { \
  51. if (!(c)) { \
  52. UTIL_DISPLAYLEVEL(1, "Error : %s, %i : %s", \
  53. __FILE__, __LINE__, #c); \
  54. exit(1); \
  55. } }
  56. /* console log */
  57. #define UTIL_DISPLAY(...) fprintf(stderr, __VA_ARGS__)
  58. #define UTIL_DISPLAYLEVEL(l, ...) { if (g_utilDisplayLevel>=l) { UTIL_DISPLAY(__VA_ARGS__); } }
  59. static int g_traceDepth = 0;
  60. int g_traceFileStat = 0;
  61. #define UTIL_TRACE_CALL(...) \
  62. { \
  63. if (g_traceFileStat) { \
  64. UTIL_DISPLAY("Trace:FileStat: %*s> ", g_traceDepth, ""); \
  65. UTIL_DISPLAY(__VA_ARGS__); \
  66. UTIL_DISPLAY("\n"); \
  67. ++g_traceDepth; \
  68. } \
  69. }
  70. #define UTIL_TRACE_RET(ret) \
  71. { \
  72. if (g_traceFileStat) { \
  73. --g_traceDepth; \
  74. UTIL_DISPLAY("Trace:FileStat: %*s< %d\n", g_traceDepth, "", (ret)); \
  75. } \
  76. }
  77. /* A modified version of realloc().
  78. * If UTIL_realloc() fails the original block is freed.
  79. */
  80. UTIL_STATIC void* UTIL_realloc(void *ptr, size_t size)
  81. {
  82. void *newptr = realloc(ptr, size);
  83. if (newptr) return newptr;
  84. free(ptr);
  85. return NULL;
  86. }
  87. #if defined(_MSC_VER)
  88. #define chmod _chmod
  89. #endif
  90. #ifndef ZSTD_HAVE_FCHMOD
  91. #if PLATFORM_POSIX_VERSION >= 199309L
  92. #define ZSTD_HAVE_FCHMOD
  93. #endif
  94. #endif
  95. #ifndef ZSTD_HAVE_FCHOWN
  96. #if PLATFORM_POSIX_VERSION >= 200809L
  97. #define ZSTD_HAVE_FCHOWN
  98. #endif
  99. #endif
  100. /*-****************************************
  101. * Console log
  102. ******************************************/
  103. int g_utilDisplayLevel;
  104. int UTIL_requireUserConfirmation(const char* prompt, const char* abortMsg,
  105. const char* acceptableLetters, int hasStdinInput) {
  106. int ch, result;
  107. if (hasStdinInput) {
  108. UTIL_DISPLAY("stdin is an input - not proceeding.\n");
  109. return 1;
  110. }
  111. UTIL_DISPLAY("%s", prompt);
  112. ch = getchar();
  113. result = 0;
  114. if (strchr(acceptableLetters, ch) == NULL) {
  115. UTIL_DISPLAY("%s \n", abortMsg);
  116. result = 1;
  117. }
  118. /* flush the rest */
  119. while ((ch!=EOF) && (ch!='\n'))
  120. ch = getchar();
  121. return result;
  122. }
  123. /*-*************************************
  124. * Constants
  125. ***************************************/
  126. #define LIST_SIZE_INCREASE (8*1024)
  127. #define MAX_FILE_OF_FILE_NAMES_SIZE (1<<20)*50
  128. /*-*************************************
  129. * Functions
  130. ***************************************/
  131. void UTIL_traceFileStat(void)
  132. {
  133. g_traceFileStat = 1;
  134. }
  135. int UTIL_fstat(const int fd, const char* filename, stat_t* statbuf)
  136. {
  137. int ret;
  138. UTIL_TRACE_CALL("UTIL_stat(%d, %s)", fd, filename);
  139. #if defined(_MSC_VER)
  140. if (fd >= 0) {
  141. ret = !_fstat64(fd, statbuf);
  142. } else {
  143. ret = !_stat64(filename, statbuf);
  144. }
  145. #elif defined(__MINGW32__) && defined (__MSVCRT__)
  146. if (fd >= 0) {
  147. ret = !_fstati64(fd, statbuf);
  148. } else {
  149. ret = !_stati64(filename, statbuf);
  150. }
  151. #else
  152. if (fd >= 0) {
  153. ret = !fstat(fd, statbuf);
  154. } else {
  155. ret = !stat(filename, statbuf);
  156. }
  157. #endif
  158. UTIL_TRACE_RET(ret);
  159. return ret;
  160. }
  161. int UTIL_stat(const char* filename, stat_t* statbuf)
  162. {
  163. return UTIL_fstat(-1, filename, statbuf);
  164. }
  165. int UTIL_isRegularFile(const char* infilename)
  166. {
  167. stat_t statbuf;
  168. int ret;
  169. UTIL_TRACE_CALL("UTIL_isRegularFile(%s)", infilename);
  170. ret = UTIL_stat(infilename, &statbuf) && UTIL_isRegularFileStat(&statbuf);
  171. UTIL_TRACE_RET(ret);
  172. return ret;
  173. }
  174. int UTIL_isRegularFileStat(const stat_t* statbuf)
  175. {
  176. #if defined(_MSC_VER)
  177. return (statbuf->st_mode & S_IFREG) != 0;
  178. #else
  179. return S_ISREG(statbuf->st_mode) != 0;
  180. #endif
  181. }
  182. /* like chmod, but avoid changing permission of /dev/null */
  183. int UTIL_chmod(char const* filename, const stat_t* statbuf, mode_t permissions)
  184. {
  185. return UTIL_fchmod(-1, filename, statbuf, permissions);
  186. }
  187. int UTIL_fchmod(const int fd, char const* filename, const stat_t* statbuf, mode_t permissions)
  188. {
  189. stat_t localStatBuf;
  190. UTIL_TRACE_CALL("UTIL_chmod(%s, %#4o)", filename, (unsigned)permissions);
  191. if (statbuf == NULL) {
  192. if (!UTIL_fstat(fd, filename, &localStatBuf)) {
  193. UTIL_TRACE_RET(0);
  194. return 0;
  195. }
  196. statbuf = &localStatBuf;
  197. }
  198. if (!UTIL_isRegularFileStat(statbuf)) {
  199. UTIL_TRACE_RET(0);
  200. return 0; /* pretend success, but don't change anything */
  201. }
  202. #ifdef ZSTD_HAVE_FCHMOD
  203. if (fd >= 0) {
  204. int ret;
  205. UTIL_TRACE_CALL("fchmod");
  206. ret = fchmod(fd, permissions);
  207. UTIL_TRACE_RET(ret);
  208. UTIL_TRACE_RET(ret);
  209. return ret;
  210. } else
  211. #endif
  212. {
  213. int ret;
  214. UTIL_TRACE_CALL("chmod");
  215. ret = chmod(filename, permissions);
  216. UTIL_TRACE_RET(ret);
  217. UTIL_TRACE_RET(ret);
  218. return ret;
  219. }
  220. }
  221. /* set access and modification times */
  222. int UTIL_utime(const char* filename, const stat_t *statbuf)
  223. {
  224. int ret;
  225. UTIL_TRACE_CALL("UTIL_utime(%s)", filename);
  226. /* We check that st_mtime is a macro here in order to give us confidence
  227. * that struct stat has a struct timespec st_mtim member. We need this
  228. * check because there are some platforms that claim to be POSIX 2008
  229. * compliant but which do not have st_mtim... */
  230. #if (PLATFORM_POSIX_VERSION >= 200809L) && defined(st_mtime)
  231. {
  232. /* (atime, mtime) */
  233. struct timespec timebuf[2] = { {0, UTIME_NOW} };
  234. timebuf[1] = statbuf->st_mtim;
  235. ret = utimensat(AT_FDCWD, filename, timebuf, 0);
  236. }
  237. #else
  238. {
  239. struct utimbuf timebuf;
  240. timebuf.actime = time(NULL);
  241. timebuf.modtime = statbuf->st_mtime;
  242. ret = utime(filename, &timebuf);
  243. }
  244. #endif
  245. errno = 0;
  246. UTIL_TRACE_RET(ret);
  247. return ret;
  248. }
  249. int UTIL_setFileStat(const char *filename, const stat_t *statbuf)
  250. {
  251. return UTIL_setFDStat(-1, filename, statbuf);
  252. }
  253. int UTIL_setFDStat(const int fd, const char *filename, const stat_t *statbuf)
  254. {
  255. int res = 0;
  256. stat_t curStatBuf;
  257. UTIL_TRACE_CALL("UTIL_setFileStat(%d, %s)", fd, filename);
  258. if (!UTIL_fstat(fd, filename, &curStatBuf) || !UTIL_isRegularFileStat(&curStatBuf)) {
  259. UTIL_TRACE_RET(-1);
  260. return -1;
  261. }
  262. /* Mimic gzip's behavior:
  263. *
  264. * "Change the group first, then the permissions, then the owner.
  265. * That way, the permissions will be correct on systems that allow
  266. * users to give away files, without introducing a security hole.
  267. * Security depends on permissions not containing the setuid or
  268. * setgid bits." */
  269. #if !defined(_WIN32)
  270. #ifdef ZSTD_HAVE_FCHOWN
  271. if (fd >= 0) {
  272. res += fchown(fd, -1, statbuf->st_gid); /* Apply group ownership */
  273. } else
  274. #endif
  275. {
  276. res += chown(filename, -1, statbuf->st_gid); /* Apply group ownership */
  277. }
  278. #endif
  279. res += UTIL_fchmod(fd, filename, &curStatBuf, statbuf->st_mode & 0777); /* Copy file permissions */
  280. #if !defined(_WIN32)
  281. #ifdef ZSTD_HAVE_FCHOWN
  282. if (fd >= 0) {
  283. res += fchown(fd, statbuf->st_uid, -1); /* Apply user ownership */
  284. } else
  285. #endif
  286. {
  287. res += chown(filename, statbuf->st_uid, -1); /* Apply user ownership */
  288. }
  289. #endif
  290. errno = 0;
  291. UTIL_TRACE_RET(-res);
  292. return -res; /* number of errors is returned */
  293. }
  294. int UTIL_isDirectory(const char* infilename)
  295. {
  296. stat_t statbuf;
  297. int ret;
  298. UTIL_TRACE_CALL("UTIL_isDirectory(%s)", infilename);
  299. ret = UTIL_stat(infilename, &statbuf) && UTIL_isDirectoryStat(&statbuf);
  300. UTIL_TRACE_RET(ret);
  301. return ret;
  302. }
  303. int UTIL_isDirectoryStat(const stat_t* statbuf)
  304. {
  305. int ret;
  306. UTIL_TRACE_CALL("UTIL_isDirectoryStat()");
  307. #if defined(_MSC_VER)
  308. ret = (statbuf->st_mode & _S_IFDIR) != 0;
  309. #else
  310. ret = S_ISDIR(statbuf->st_mode) != 0;
  311. #endif
  312. UTIL_TRACE_RET(ret);
  313. return ret;
  314. }
  315. int UTIL_compareStr(const void *p1, const void *p2) {
  316. return strcmp(* (char * const *) p1, * (char * const *) p2);
  317. }
  318. int UTIL_isSameFile(const char* fName1, const char* fName2)
  319. {
  320. int ret;
  321. assert(fName1 != NULL); assert(fName2 != NULL);
  322. UTIL_TRACE_CALL("UTIL_isSameFile(%s, %s)", fName1, fName2);
  323. #if defined(_MSC_VER) || defined(_WIN32)
  324. /* note : Visual does not support file identification by inode.
  325. * inode does not work on Windows, even with a posix layer, like msys2.
  326. * The following work-around is limited to detecting exact name repetition only,
  327. * aka `filename` is considered different from `subdir/../filename` */
  328. ret = !strcmp(fName1, fName2);
  329. #else
  330. { stat_t file1Stat;
  331. stat_t file2Stat;
  332. ret = UTIL_stat(fName1, &file1Stat)
  333. && UTIL_stat(fName2, &file2Stat)
  334. && UTIL_isSameFileStat(fName1, fName2, &file1Stat, &file2Stat);
  335. }
  336. #endif
  337. UTIL_TRACE_RET(ret);
  338. return ret;
  339. }
  340. int UTIL_isSameFileStat(
  341. const char* fName1, const char* fName2,
  342. const stat_t* file1Stat, const stat_t* file2Stat)
  343. {
  344. int ret;
  345. assert(fName1 != NULL); assert(fName2 != NULL);
  346. UTIL_TRACE_CALL("UTIL_isSameFileStat(%s, %s)", fName1, fName2);
  347. #if defined(_MSC_VER) || defined(_WIN32)
  348. /* note : Visual does not support file identification by inode.
  349. * inode does not work on Windows, even with a posix layer, like msys2.
  350. * The following work-around is limited to detecting exact name repetition only,
  351. * aka `filename` is considered different from `subdir/../filename` */
  352. (void)file1Stat;
  353. (void)file2Stat;
  354. ret = !strcmp(fName1, fName2);
  355. #else
  356. {
  357. ret = (file1Stat->st_dev == file2Stat->st_dev)
  358. && (file1Stat->st_ino == file2Stat->st_ino);
  359. }
  360. #endif
  361. UTIL_TRACE_RET(ret);
  362. return ret;
  363. }
  364. /* UTIL_isFIFO : distinguish named pipes */
  365. int UTIL_isFIFO(const char* infilename)
  366. {
  367. UTIL_TRACE_CALL("UTIL_isFIFO(%s)", infilename);
  368. /* macro guards, as defined in : https://linux.die.net/man/2/lstat */
  369. #if PLATFORM_POSIX_VERSION >= 200112L
  370. {
  371. stat_t statbuf;
  372. if (UTIL_stat(infilename, &statbuf) && UTIL_isFIFOStat(&statbuf)) {
  373. UTIL_TRACE_RET(1);
  374. return 1;
  375. }
  376. }
  377. #endif
  378. (void)infilename;
  379. UTIL_TRACE_RET(0);
  380. return 0;
  381. }
  382. /* UTIL_isFIFO : distinguish named pipes */
  383. int UTIL_isFIFOStat(const stat_t* statbuf)
  384. {
  385. /* macro guards, as defined in : https://linux.die.net/man/2/lstat */
  386. #if PLATFORM_POSIX_VERSION >= 200112L
  387. if (S_ISFIFO(statbuf->st_mode)) return 1;
  388. #endif
  389. (void)statbuf;
  390. return 0;
  391. }
  392. /* UTIL_isBlockDevStat : distinguish named pipes */
  393. int UTIL_isBlockDevStat(const stat_t* statbuf)
  394. {
  395. /* macro guards, as defined in : https://linux.die.net/man/2/lstat */
  396. #if PLATFORM_POSIX_VERSION >= 200112L
  397. if (S_ISBLK(statbuf->st_mode)) return 1;
  398. #endif
  399. (void)statbuf;
  400. return 0;
  401. }
  402. int UTIL_isLink(const char* infilename)
  403. {
  404. UTIL_TRACE_CALL("UTIL_isLink(%s)", infilename);
  405. /* macro guards, as defined in : https://linux.die.net/man/2/lstat */
  406. #if PLATFORM_POSIX_VERSION >= 200112L
  407. {
  408. stat_t statbuf;
  409. int const r = lstat(infilename, &statbuf);
  410. if (!r && S_ISLNK(statbuf.st_mode)) {
  411. UTIL_TRACE_RET(1);
  412. return 1;
  413. }
  414. }
  415. #endif
  416. (void)infilename;
  417. UTIL_TRACE_RET(0);
  418. return 0;
  419. }
  420. static int g_fakeStdinIsConsole = 0;
  421. static int g_fakeStderrIsConsole = 0;
  422. static int g_fakeStdoutIsConsole = 0;
  423. int UTIL_isConsole(FILE* file)
  424. {
  425. int ret;
  426. UTIL_TRACE_CALL("UTIL_isConsole(%d)", fileno(file));
  427. if (file == stdin && g_fakeStdinIsConsole)
  428. ret = 1;
  429. else if (file == stderr && g_fakeStderrIsConsole)
  430. ret = 1;
  431. else if (file == stdout && g_fakeStdoutIsConsole)
  432. ret = 1;
  433. else
  434. ret = IS_CONSOLE(file);
  435. UTIL_TRACE_RET(ret);
  436. return ret;
  437. }
  438. void UTIL_fakeStdinIsConsole(void)
  439. {
  440. g_fakeStdinIsConsole = 1;
  441. }
  442. void UTIL_fakeStdoutIsConsole(void)
  443. {
  444. g_fakeStdoutIsConsole = 1;
  445. }
  446. void UTIL_fakeStderrIsConsole(void)
  447. {
  448. g_fakeStderrIsConsole = 1;
  449. }
  450. U64 UTIL_getFileSize(const char* infilename)
  451. {
  452. stat_t statbuf;
  453. UTIL_TRACE_CALL("UTIL_getFileSize(%s)", infilename);
  454. if (!UTIL_stat(infilename, &statbuf)) {
  455. UTIL_TRACE_RET(-1);
  456. return UTIL_FILESIZE_UNKNOWN;
  457. }
  458. {
  459. U64 const size = UTIL_getFileSizeStat(&statbuf);
  460. UTIL_TRACE_RET((int)size);
  461. return size;
  462. }
  463. }
  464. U64 UTIL_getFileSizeStat(const stat_t* statbuf)
  465. {
  466. if (!UTIL_isRegularFileStat(statbuf)) return UTIL_FILESIZE_UNKNOWN;
  467. #if defined(_MSC_VER)
  468. if (!(statbuf->st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
  469. #elif defined(__MINGW32__) && defined (__MSVCRT__)
  470. if (!(statbuf->st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
  471. #else
  472. if (!S_ISREG(statbuf->st_mode)) return UTIL_FILESIZE_UNKNOWN;
  473. #endif
  474. return (U64)statbuf->st_size;
  475. }
  476. UTIL_HumanReadableSize_t UTIL_makeHumanReadableSize(U64 size)
  477. {
  478. UTIL_HumanReadableSize_t hrs;
  479. if (g_utilDisplayLevel > 3) {
  480. /* In verbose mode, do not scale sizes down, except in the case of
  481. * values that exceed the integral precision of a double. */
  482. if (size >= (1ull << 53)) {
  483. hrs.value = (double)size / (1ull << 20);
  484. hrs.suffix = " MiB";
  485. /* At worst, a double representation of a maximal size will be
  486. * accurate to better than tens of kilobytes. */
  487. hrs.precision = 2;
  488. } else {
  489. hrs.value = (double)size;
  490. hrs.suffix = " B";
  491. hrs.precision = 0;
  492. }
  493. } else {
  494. /* In regular mode, scale sizes down and use suffixes. */
  495. if (size >= (1ull << 60)) {
  496. hrs.value = (double)size / (1ull << 60);
  497. hrs.suffix = " EiB";
  498. } else if (size >= (1ull << 50)) {
  499. hrs.value = (double)size / (1ull << 50);
  500. hrs.suffix = " PiB";
  501. } else if (size >= (1ull << 40)) {
  502. hrs.value = (double)size / (1ull << 40);
  503. hrs.suffix = " TiB";
  504. } else if (size >= (1ull << 30)) {
  505. hrs.value = (double)size / (1ull << 30);
  506. hrs.suffix = " GiB";
  507. } else if (size >= (1ull << 20)) {
  508. hrs.value = (double)size / (1ull << 20);
  509. hrs.suffix = " MiB";
  510. } else if (size >= (1ull << 10)) {
  511. hrs.value = (double)size / (1ull << 10);
  512. hrs.suffix = " KiB";
  513. } else {
  514. hrs.value = (double)size;
  515. hrs.suffix = " B";
  516. }
  517. if (hrs.value >= 100 || (U64)hrs.value == size) {
  518. hrs.precision = 0;
  519. } else if (hrs.value >= 10) {
  520. hrs.precision = 1;
  521. } else if (hrs.value > 1) {
  522. hrs.precision = 2;
  523. } else {
  524. hrs.precision = 3;
  525. }
  526. }
  527. return hrs;
  528. }
  529. U64 UTIL_getTotalFileSize(const char* const * fileNamesTable, unsigned nbFiles)
  530. {
  531. U64 total = 0;
  532. unsigned n;
  533. UTIL_TRACE_CALL("UTIL_getTotalFileSize(%u)", nbFiles);
  534. for (n=0; n<nbFiles; n++) {
  535. U64 const size = UTIL_getFileSize(fileNamesTable[n]);
  536. if (size == UTIL_FILESIZE_UNKNOWN) {
  537. UTIL_TRACE_RET(-1);
  538. return UTIL_FILESIZE_UNKNOWN;
  539. }
  540. total += size;
  541. }
  542. UTIL_TRACE_RET((int)total);
  543. return total;
  544. }
  545. /* condition : @file must be valid, and not have reached its end.
  546. * @return : length of line written into @buf, ended with `\0` instead of '\n',
  547. * or 0, if there is no new line */
  548. static size_t readLineFromFile(char* buf, size_t len, FILE* file)
  549. {
  550. assert(!feof(file));
  551. if ( fgets(buf, (int) len, file) == NULL ) return 0;
  552. { size_t linelen = strlen(buf);
  553. if (strlen(buf)==0) return 0;
  554. if (buf[linelen-1] == '\n') linelen--;
  555. buf[linelen] = '\0';
  556. return linelen+1;
  557. }
  558. }
  559. /* Conditions :
  560. * size of @inputFileName file must be < @dstCapacity
  561. * @dst must be initialized
  562. * @return : nb of lines
  563. * or -1 if there's an error
  564. */
  565. static int
  566. readLinesFromFile(void* dst, size_t dstCapacity,
  567. const char* inputFileName)
  568. {
  569. int nbFiles = 0;
  570. size_t pos = 0;
  571. char* const buf = (char*)dst;
  572. FILE* const inputFile = fopen(inputFileName, "r");
  573. assert(dst != NULL);
  574. if(!inputFile) {
  575. if (g_utilDisplayLevel >= 1) perror("zstd:util:readLinesFromFile");
  576. return -1;
  577. }
  578. while ( !feof(inputFile) ) {
  579. size_t const lineLength = readLineFromFile(buf+pos, dstCapacity-pos, inputFile);
  580. if (lineLength == 0) break;
  581. assert(pos + lineLength <= dstCapacity); /* '=' for inputFile not terminated with '\n' */
  582. pos += lineLength;
  583. ++nbFiles;
  584. }
  585. CONTROL( fclose(inputFile) == 0 );
  586. return nbFiles;
  587. }
  588. /*Note: buf is not freed in case function successfully created table because filesTable->fileNames[0] = buf*/
  589. FileNamesTable*
  590. UTIL_createFileNamesTable_fromFileName(const char* inputFileName)
  591. {
  592. size_t nbFiles = 0;
  593. char* buf;
  594. size_t bufSize;
  595. size_t pos = 0;
  596. stat_t statbuf;
  597. if (!UTIL_stat(inputFileName, &statbuf) || !UTIL_isRegularFileStat(&statbuf))
  598. return NULL;
  599. { U64 const inputFileSize = UTIL_getFileSizeStat(&statbuf);
  600. if(inputFileSize > MAX_FILE_OF_FILE_NAMES_SIZE)
  601. return NULL;
  602. bufSize = (size_t)(inputFileSize + 1); /* (+1) to add '\0' at the end of last filename */
  603. }
  604. buf = (char*) malloc(bufSize);
  605. CONTROL( buf != NULL );
  606. { int const ret_nbFiles = readLinesFromFile(buf, bufSize, inputFileName);
  607. if (ret_nbFiles <= 0) {
  608. free(buf);
  609. return NULL;
  610. }
  611. nbFiles = (size_t)ret_nbFiles;
  612. }
  613. { const char** filenamesTable = (const char**) malloc(nbFiles * sizeof(*filenamesTable));
  614. CONTROL(filenamesTable != NULL);
  615. { size_t fnb;
  616. for (fnb = 0, pos = 0; fnb < nbFiles; fnb++) {
  617. filenamesTable[fnb] = buf+pos;
  618. pos += strlen(buf+pos)+1; /* +1 for the finishing `\0` */
  619. } }
  620. assert(pos <= bufSize);
  621. return UTIL_assembleFileNamesTable(filenamesTable, nbFiles, buf);
  622. }
  623. }
  624. static FileNamesTable*
  625. UTIL_assembleFileNamesTable2(const char** filenames, size_t tableSize, size_t tableCapacity, char* buf)
  626. {
  627. FileNamesTable* const table = (FileNamesTable*) malloc(sizeof(*table));
  628. CONTROL(table != NULL);
  629. table->fileNames = filenames;
  630. table->buf = buf;
  631. table->tableSize = tableSize;
  632. table->tableCapacity = tableCapacity;
  633. return table;
  634. }
  635. FileNamesTable*
  636. UTIL_assembleFileNamesTable(const char** filenames, size_t tableSize, char* buf)
  637. {
  638. return UTIL_assembleFileNamesTable2(filenames, tableSize, tableSize, buf);
  639. }
  640. void UTIL_freeFileNamesTable(FileNamesTable* table)
  641. {
  642. if (table==NULL) return;
  643. free((void*)table->fileNames);
  644. free(table->buf);
  645. free(table);
  646. }
  647. FileNamesTable* UTIL_allocateFileNamesTable(size_t tableSize)
  648. {
  649. const char** const fnTable = (const char**)malloc(tableSize * sizeof(*fnTable));
  650. FileNamesTable* fnt;
  651. if (fnTable==NULL) return NULL;
  652. fnt = UTIL_assembleFileNamesTable(fnTable, tableSize, NULL);
  653. fnt->tableSize = 0; /* the table is empty */
  654. return fnt;
  655. }
  656. int UTIL_searchFileNamesTable(FileNamesTable* table, char const* name) {
  657. size_t i;
  658. for(i=0 ;i < table->tableSize; i++) {
  659. if(!strcmp(table->fileNames[i], name)) {
  660. return (int)i;
  661. }
  662. }
  663. return -1;
  664. }
  665. void UTIL_refFilename(FileNamesTable* fnt, const char* filename)
  666. {
  667. assert(fnt->tableSize < fnt->tableCapacity);
  668. fnt->fileNames[fnt->tableSize] = filename;
  669. fnt->tableSize++;
  670. }
  671. static size_t getTotalTableSize(FileNamesTable* table)
  672. {
  673. size_t fnb = 0, totalSize = 0;
  674. for(fnb = 0 ; fnb < table->tableSize && table->fileNames[fnb] ; ++fnb) {
  675. totalSize += strlen(table->fileNames[fnb]) + 1; /* +1 to add '\0' at the end of each fileName */
  676. }
  677. return totalSize;
  678. }
  679. FileNamesTable*
  680. UTIL_mergeFileNamesTable(FileNamesTable* table1, FileNamesTable* table2)
  681. {
  682. unsigned newTableIdx = 0;
  683. size_t pos = 0;
  684. size_t newTotalTableSize;
  685. char* buf;
  686. FileNamesTable* const newTable = UTIL_assembleFileNamesTable(NULL, 0, NULL);
  687. CONTROL( newTable != NULL );
  688. newTotalTableSize = getTotalTableSize(table1) + getTotalTableSize(table2);
  689. buf = (char*) calloc(newTotalTableSize, sizeof(*buf));
  690. CONTROL ( buf != NULL );
  691. newTable->buf = buf;
  692. newTable->tableSize = table1->tableSize + table2->tableSize;
  693. newTable->fileNames = (const char **) calloc(newTable->tableSize, sizeof(*(newTable->fileNames)));
  694. CONTROL ( newTable->fileNames != NULL );
  695. { unsigned idx1;
  696. for( idx1=0 ; (idx1 < table1->tableSize) && table1->fileNames[idx1] && (pos < newTotalTableSize); ++idx1, ++newTableIdx) {
  697. size_t const curLen = strlen(table1->fileNames[idx1]);
  698. memcpy(buf+pos, table1->fileNames[idx1], curLen);
  699. assert(newTableIdx <= newTable->tableSize);
  700. newTable->fileNames[newTableIdx] = buf+pos;
  701. pos += curLen+1;
  702. } }
  703. { unsigned idx2;
  704. for( idx2=0 ; (idx2 < table2->tableSize) && table2->fileNames[idx2] && (pos < newTotalTableSize) ; ++idx2, ++newTableIdx) {
  705. size_t const curLen = strlen(table2->fileNames[idx2]);
  706. memcpy(buf+pos, table2->fileNames[idx2], curLen);
  707. assert(newTableIdx < newTable->tableSize);
  708. newTable->fileNames[newTableIdx] = buf+pos;
  709. pos += curLen+1;
  710. } }
  711. assert(pos <= newTotalTableSize);
  712. newTable->tableSize = newTableIdx;
  713. UTIL_freeFileNamesTable(table1);
  714. UTIL_freeFileNamesTable(table2);
  715. return newTable;
  716. }
  717. #ifdef _WIN32
  718. static int UTIL_prepareFileList(const char* dirName,
  719. char** bufStart, size_t* pos,
  720. char** bufEnd, int followLinks)
  721. {
  722. char* path;
  723. size_t dirLength, pathLength;
  724. int nbFiles = 0;
  725. WIN32_FIND_DATAA cFile;
  726. HANDLE hFile;
  727. dirLength = strlen(dirName);
  728. path = (char*) malloc(dirLength + 3);
  729. if (!path) return 0;
  730. memcpy(path, dirName, dirLength);
  731. path[dirLength] = '\\';
  732. path[dirLength+1] = '*';
  733. path[dirLength+2] = 0;
  734. hFile=FindFirstFileA(path, &cFile);
  735. if (hFile == INVALID_HANDLE_VALUE) {
  736. UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s'\n", dirName);
  737. return 0;
  738. }
  739. free(path);
  740. do {
  741. size_t const fnameLength = strlen(cFile.cFileName);
  742. path = (char*) malloc(dirLength + fnameLength + 2);
  743. if (!path) { FindClose(hFile); return 0; }
  744. memcpy(path, dirName, dirLength);
  745. path[dirLength] = '\\';
  746. memcpy(path+dirLength+1, cFile.cFileName, fnameLength);
  747. pathLength = dirLength+1+fnameLength;
  748. path[pathLength] = 0;
  749. if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  750. if ( strcmp (cFile.cFileName, "..") == 0
  751. || strcmp (cFile.cFileName, ".") == 0 )
  752. continue;
  753. /* Recursively call "UTIL_prepareFileList" with the new path. */
  754. nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks);
  755. if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
  756. } else if ( (cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL)
  757. || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
  758. || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) ) {
  759. if (*bufStart + *pos + pathLength >= *bufEnd) {
  760. ptrdiff_t const newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
  761. *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
  762. if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
  763. *bufEnd = *bufStart + newListSize;
  764. }
  765. if (*bufStart + *pos + pathLength < *bufEnd) {
  766. memcpy(*bufStart + *pos, path, pathLength+1 /* include final \0 */);
  767. *pos += pathLength + 1;
  768. nbFiles++;
  769. } }
  770. free(path);
  771. } while (FindNextFileA(hFile, &cFile));
  772. FindClose(hFile);
  773. return nbFiles;
  774. }
  775. #elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */
  776. static int UTIL_prepareFileList(const char *dirName,
  777. char** bufStart, size_t* pos,
  778. char** bufEnd, int followLinks)
  779. {
  780. DIR* dir;
  781. struct dirent * entry;
  782. size_t dirLength;
  783. int nbFiles = 0;
  784. if (!(dir = opendir(dirName))) {
  785. UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
  786. return 0;
  787. }
  788. dirLength = strlen(dirName);
  789. errno = 0;
  790. while ((entry = readdir(dir)) != NULL) {
  791. char* path;
  792. size_t fnameLength, pathLength;
  793. if (strcmp (entry->d_name, "..") == 0 ||
  794. strcmp (entry->d_name, ".") == 0) continue;
  795. fnameLength = strlen(entry->d_name);
  796. path = (char*) malloc(dirLength + fnameLength + 2);
  797. if (!path) { closedir(dir); return 0; }
  798. memcpy(path, dirName, dirLength);
  799. path[dirLength] = '/';
  800. memcpy(path+dirLength+1, entry->d_name, fnameLength);
  801. pathLength = dirLength+1+fnameLength;
  802. path[pathLength] = 0;
  803. if (!followLinks && UTIL_isLink(path)) {
  804. UTIL_DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", path);
  805. free(path);
  806. continue;
  807. }
  808. if (UTIL_isDirectory(path)) {
  809. nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks); /* Recursively call "UTIL_prepareFileList" with the new path. */
  810. if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
  811. } else {
  812. if (*bufStart + *pos + pathLength >= *bufEnd) {
  813. ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
  814. assert(newListSize >= 0);
  815. *bufStart = (char*)UTIL_realloc(*bufStart, (size_t)newListSize);
  816. if (*bufStart != NULL) {
  817. *bufEnd = *bufStart + newListSize;
  818. } else {
  819. free(path); closedir(dir); return 0;
  820. }
  821. }
  822. if (*bufStart + *pos + pathLength < *bufEnd) {
  823. memcpy(*bufStart + *pos, path, pathLength + 1); /* with final \0 */
  824. *pos += pathLength + 1;
  825. nbFiles++;
  826. } }
  827. free(path);
  828. errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */
  829. }
  830. if (errno != 0) {
  831. UTIL_DISPLAYLEVEL(1, "readdir(%s) error: %s \n", dirName, strerror(errno));
  832. free(*bufStart);
  833. *bufStart = NULL;
  834. }
  835. closedir(dir);
  836. return nbFiles;
  837. }
  838. #else
  839. static int UTIL_prepareFileList(const char *dirName,
  840. char** bufStart, size_t* pos,
  841. char** bufEnd, int followLinks)
  842. {
  843. (void)bufStart; (void)bufEnd; (void)pos; (void)followLinks;
  844. UTIL_DISPLAYLEVEL(1, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE) \n", dirName);
  845. return 0;
  846. }
  847. #endif /* #ifdef _WIN32 */
  848. int UTIL_isCompressedFile(const char *inputName, const char *extensionList[])
  849. {
  850. const char* ext = UTIL_getFileExtension(inputName);
  851. while(*extensionList!=NULL)
  852. {
  853. const int isCompressedExtension = strcmp(ext,*extensionList);
  854. if(isCompressedExtension==0)
  855. return 1;
  856. ++extensionList;
  857. }
  858. return 0;
  859. }
  860. /*Utility function to get file extension from file */
  861. const char* UTIL_getFileExtension(const char* infilename)
  862. {
  863. const char* extension = strrchr(infilename, '.');
  864. if(!extension || extension==infilename) return "";
  865. return extension;
  866. }
  867. static int pathnameHas2Dots(const char *pathname)
  868. {
  869. /* We need to figure out whether any ".." present in the path is a whole
  870. * path token, which is the case if it is bordered on both sides by either
  871. * the beginning/end of the path or by a directory separator.
  872. */
  873. const char *needle = pathname;
  874. while (1) {
  875. needle = strstr(needle, "..");
  876. if (needle == NULL) {
  877. return 0;
  878. }
  879. if ((needle == pathname || needle[-1] == PATH_SEP)
  880. && (needle[2] == '\0' || needle[2] == PATH_SEP)) {
  881. return 1;
  882. }
  883. /* increment so we search for the next match */
  884. needle++;
  885. };
  886. return 0;
  887. }
  888. static int isFileNameValidForMirroredOutput(const char *filename)
  889. {
  890. return !pathnameHas2Dots(filename);
  891. }
  892. #define DIR_DEFAULT_MODE 0755
  893. static mode_t getDirMode(const char *dirName)
  894. {
  895. stat_t st;
  896. if (!UTIL_stat(dirName, &st)) {
  897. UTIL_DISPLAY("zstd: failed to get DIR stats %s: %s\n", dirName, strerror(errno));
  898. return DIR_DEFAULT_MODE;
  899. }
  900. if (!UTIL_isDirectoryStat(&st)) {
  901. UTIL_DISPLAY("zstd: expected directory: %s\n", dirName);
  902. return DIR_DEFAULT_MODE;
  903. }
  904. return st.st_mode;
  905. }
  906. static int makeDir(const char *dir, mode_t mode)
  907. {
  908. #if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__)
  909. int ret = _mkdir(dir);
  910. (void) mode;
  911. #else
  912. int ret = mkdir(dir, mode);
  913. #endif
  914. if (ret != 0) {
  915. if (errno == EEXIST)
  916. return 0;
  917. UTIL_DISPLAY("zstd: failed to create DIR %s: %s\n", dir, strerror(errno));
  918. }
  919. return ret;
  920. }
  921. /* this function requires a mutable input string */
  922. static void convertPathnameToDirName(char *pathname)
  923. {
  924. size_t len = 0;
  925. char* pos = NULL;
  926. /* get dir name from pathname similar to 'dirname()' */
  927. assert(pathname != NULL);
  928. /* remove trailing '/' chars */
  929. len = strlen(pathname);
  930. assert(len > 0);
  931. while (pathname[len] == PATH_SEP) {
  932. pathname[len] = '\0';
  933. len--;
  934. }
  935. if (len == 0) return;
  936. /* if input is a single file, return '.' instead. i.e.
  937. * "xyz/abc/file.txt" => "xyz/abc"
  938. "./file.txt" => "."
  939. "file.txt" => "."
  940. */
  941. pos = strrchr(pathname, PATH_SEP);
  942. if (pos == NULL) {
  943. pathname[0] = '.';
  944. pathname[1] = '\0';
  945. } else {
  946. *pos = '\0';
  947. }
  948. }
  949. /* pathname must be valid */
  950. static const char* trimLeadingRootChar(const char *pathname)
  951. {
  952. assert(pathname != NULL);
  953. if (pathname[0] == PATH_SEP)
  954. return pathname + 1;
  955. return pathname;
  956. }
  957. /* pathname must be valid */
  958. static const char* trimLeadingCurrentDirConst(const char *pathname)
  959. {
  960. assert(pathname != NULL);
  961. if ((pathname[0] == '.') && (pathname[1] == PATH_SEP))
  962. return pathname + 2;
  963. return pathname;
  964. }
  965. static char*
  966. trimLeadingCurrentDir(char *pathname)
  967. {
  968. /* 'union charunion' can do const-cast without compiler warning */
  969. union charunion {
  970. char *chr;
  971. const char* cchr;
  972. } ptr;
  973. ptr.cchr = trimLeadingCurrentDirConst(pathname);
  974. return ptr.chr;
  975. }
  976. /* remove leading './' or '/' chars here */
  977. static const char * trimPath(const char *pathname)
  978. {
  979. return trimLeadingRootChar(
  980. trimLeadingCurrentDirConst(pathname));
  981. }
  982. static char* mallocAndJoin2Dir(const char *dir1, const char *dir2)
  983. {
  984. assert(dir1 != NULL && dir2 != NULL);
  985. { const size_t dir1Size = strlen(dir1);
  986. const size_t dir2Size = strlen(dir2);
  987. char *outDirBuffer, *buffer;
  988. outDirBuffer = (char *) malloc(dir1Size + dir2Size + 2);
  989. CONTROL(outDirBuffer != NULL);
  990. memcpy(outDirBuffer, dir1, dir1Size);
  991. outDirBuffer[dir1Size] = '\0';
  992. if (dir2[0] == '.')
  993. return outDirBuffer;
  994. buffer = outDirBuffer + dir1Size;
  995. if (dir1Size > 0 && *(buffer - 1) != PATH_SEP) {
  996. *buffer = PATH_SEP;
  997. buffer++;
  998. }
  999. memcpy(buffer, dir2, dir2Size);
  1000. buffer[dir2Size] = '\0';
  1001. return outDirBuffer;
  1002. }
  1003. }
  1004. /* this function will return NULL if input srcFileName is not valid name for mirrored output path */
  1005. char* UTIL_createMirroredDestDirName(const char* srcFileName, const char* outDirRootName)
  1006. {
  1007. char* pathname = NULL;
  1008. if (!isFileNameValidForMirroredOutput(srcFileName))
  1009. return NULL;
  1010. pathname = mallocAndJoin2Dir(outDirRootName, trimPath(srcFileName));
  1011. convertPathnameToDirName(pathname);
  1012. return pathname;
  1013. }
  1014. static int
  1015. mirrorSrcDir(char* srcDirName, const char* outDirName)
  1016. {
  1017. mode_t srcMode;
  1018. int status = 0;
  1019. char* newDir = mallocAndJoin2Dir(outDirName, trimPath(srcDirName));
  1020. if (!newDir)
  1021. return -ENOMEM;
  1022. srcMode = getDirMode(srcDirName);
  1023. status = makeDir(newDir, srcMode);
  1024. free(newDir);
  1025. return status;
  1026. }
  1027. static int
  1028. mirrorSrcDirRecursive(char* srcDirName, const char* outDirName)
  1029. {
  1030. int status = 0;
  1031. char* pp = trimLeadingCurrentDir(srcDirName);
  1032. char* sp = NULL;
  1033. while ((sp = strchr(pp, PATH_SEP)) != NULL) {
  1034. if (sp != pp) {
  1035. *sp = '\0';
  1036. status = mirrorSrcDir(srcDirName, outDirName);
  1037. if (status != 0)
  1038. return status;
  1039. *sp = PATH_SEP;
  1040. }
  1041. pp = sp + 1;
  1042. }
  1043. status = mirrorSrcDir(srcDirName, outDirName);
  1044. return status;
  1045. }
  1046. static void
  1047. makeMirroredDestDirsWithSameSrcDirMode(char** srcDirNames, unsigned nbFile, const char* outDirName)
  1048. {
  1049. unsigned int i = 0;
  1050. for (i = 0; i < nbFile; i++)
  1051. mirrorSrcDirRecursive(srcDirNames[i], outDirName);
  1052. }
  1053. static int
  1054. firstIsParentOrSameDirOfSecond(const char* firstDir, const char* secondDir)
  1055. {
  1056. size_t firstDirLen = strlen(firstDir),
  1057. secondDirLen = strlen(secondDir);
  1058. return firstDirLen <= secondDirLen &&
  1059. (secondDir[firstDirLen] == PATH_SEP || secondDir[firstDirLen] == '\0') &&
  1060. 0 == strncmp(firstDir, secondDir, firstDirLen);
  1061. }
  1062. static int compareDir(const void* pathname1, const void* pathname2) {
  1063. /* sort it after remove the leading '/' or './'*/
  1064. const char* s1 = trimPath(*(char * const *) pathname1);
  1065. const char* s2 = trimPath(*(char * const *) pathname2);
  1066. return strcmp(s1, s2);
  1067. }
  1068. static void
  1069. makeUniqueMirroredDestDirs(char** srcDirNames, unsigned nbFile, const char* outDirName)
  1070. {
  1071. unsigned int i = 0, uniqueDirNr = 0;
  1072. char** uniqueDirNames = NULL;
  1073. if (nbFile == 0)
  1074. return;
  1075. uniqueDirNames = (char** ) malloc(nbFile * sizeof (char *));
  1076. CONTROL(uniqueDirNames != NULL);
  1077. /* if dirs is "a/b/c" and "a/b/c/d", we only need call:
  1078. * we just need "a/b/c/d" */
  1079. qsort((void *)srcDirNames, nbFile, sizeof(char*), compareDir);
  1080. uniqueDirNr = 1;
  1081. uniqueDirNames[uniqueDirNr - 1] = srcDirNames[0];
  1082. for (i = 1; i < nbFile; i++) {
  1083. char* prevDirName = srcDirNames[i - 1];
  1084. char* currDirName = srcDirNames[i];
  1085. /* note: we always compare trimmed path, i.e.:
  1086. * src dir of "./foo" and "/foo" will be both saved into:
  1087. * "outDirName/foo/" */
  1088. if (!firstIsParentOrSameDirOfSecond(trimPath(prevDirName),
  1089. trimPath(currDirName)))
  1090. uniqueDirNr++;
  1091. /* we need to maintain original src dir name instead of trimmed
  1092. * dir, so we can retrieve the original src dir's mode_t */
  1093. uniqueDirNames[uniqueDirNr - 1] = currDirName;
  1094. }
  1095. makeMirroredDestDirsWithSameSrcDirMode(uniqueDirNames, uniqueDirNr, outDirName);
  1096. free(uniqueDirNames);
  1097. }
  1098. static void
  1099. makeMirroredDestDirs(char** srcFileNames, unsigned nbFile, const char* outDirName)
  1100. {
  1101. unsigned int i = 0;
  1102. for (i = 0; i < nbFile; ++i)
  1103. convertPathnameToDirName(srcFileNames[i]);
  1104. makeUniqueMirroredDestDirs(srcFileNames, nbFile, outDirName);
  1105. }
  1106. void UTIL_mirrorSourceFilesDirectories(const char** inFileNames, unsigned int nbFile, const char* outDirName)
  1107. {
  1108. unsigned int i = 0, validFilenamesNr = 0;
  1109. char** srcFileNames = (char **) malloc(nbFile * sizeof (char *));
  1110. CONTROL(srcFileNames != NULL);
  1111. /* check input filenames is valid */
  1112. for (i = 0; i < nbFile; ++i) {
  1113. if (isFileNameValidForMirroredOutput(inFileNames[i])) {
  1114. char* fname = STRDUP(inFileNames[i]);
  1115. CONTROL(fname != NULL);
  1116. srcFileNames[validFilenamesNr++] = fname;
  1117. }
  1118. }
  1119. if (validFilenamesNr > 0) {
  1120. makeDir(outDirName, DIR_DEFAULT_MODE);
  1121. makeMirroredDestDirs(srcFileNames, validFilenamesNr, outDirName);
  1122. }
  1123. for (i = 0; i < validFilenamesNr; i++)
  1124. free(srcFileNames[i]);
  1125. free(srcFileNames);
  1126. }
  1127. FileNamesTable*
  1128. UTIL_createExpandedFNT(const char* const* inputNames, size_t nbIfns, int followLinks)
  1129. {
  1130. unsigned nbFiles;
  1131. char* buf = (char*)malloc(LIST_SIZE_INCREASE);
  1132. char* bufend = buf + LIST_SIZE_INCREASE;
  1133. if (!buf) return NULL;
  1134. { size_t ifnNb, pos;
  1135. for (ifnNb=0, pos=0, nbFiles=0; ifnNb<nbIfns; ifnNb++) {
  1136. if (!UTIL_isDirectory(inputNames[ifnNb])) {
  1137. size_t const len = strlen(inputNames[ifnNb]);
  1138. if (buf + pos + len >= bufend) {
  1139. ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE;
  1140. assert(newListSize >= 0);
  1141. buf = (char*)UTIL_realloc(buf, (size_t)newListSize);
  1142. if (!buf) return NULL;
  1143. bufend = buf + newListSize;
  1144. }
  1145. if (buf + pos + len < bufend) {
  1146. memcpy(buf+pos, inputNames[ifnNb], len+1); /* including final \0 */
  1147. pos += len + 1;
  1148. nbFiles++;
  1149. }
  1150. } else {
  1151. nbFiles += (unsigned)UTIL_prepareFileList(inputNames[ifnNb], &buf, &pos, &bufend, followLinks);
  1152. if (buf == NULL) return NULL;
  1153. } } }
  1154. /* note : even if nbFiles==0, function returns a valid, though empty, FileNamesTable* object */
  1155. { size_t ifnNb, pos;
  1156. size_t const fntCapacity = nbFiles + 1; /* minimum 1, allows adding one reference, typically stdin */
  1157. const char** const fileNamesTable = (const char**)malloc(fntCapacity * sizeof(*fileNamesTable));
  1158. if (!fileNamesTable) { free(buf); return NULL; }
  1159. for (ifnNb = 0, pos = 0; ifnNb < nbFiles; ifnNb++) {
  1160. fileNamesTable[ifnNb] = buf + pos;
  1161. if (buf + pos > bufend) { free(buf); free((void*)fileNamesTable); return NULL; }
  1162. pos += strlen(fileNamesTable[ifnNb]) + 1;
  1163. }
  1164. return UTIL_assembleFileNamesTable2(fileNamesTable, nbFiles, fntCapacity, buf);
  1165. }
  1166. }
  1167. void UTIL_expandFNT(FileNamesTable** fnt, int followLinks)
  1168. {
  1169. FileNamesTable* const newFNT = UTIL_createExpandedFNT((*fnt)->fileNames, (*fnt)->tableSize, followLinks);
  1170. CONTROL(newFNT != NULL);
  1171. UTIL_freeFileNamesTable(*fnt);
  1172. *fnt = newFNT;
  1173. }
  1174. FileNamesTable* UTIL_createFNT_fromROTable(const char** filenames, size_t nbFilenames)
  1175. {
  1176. size_t const sizeof_FNTable = nbFilenames * sizeof(*filenames);
  1177. const char** const newFNTable = (const char**)malloc(sizeof_FNTable);
  1178. if (newFNTable==NULL) return NULL;
  1179. memcpy((void*)newFNTable, filenames, sizeof_FNTable); /* void* : mitigate a Visual compiler bug or limitation */
  1180. return UTIL_assembleFileNamesTable(newFNTable, nbFilenames, NULL);
  1181. }
  1182. /*-****************************************
  1183. * count the number of cores
  1184. ******************************************/
  1185. #if defined(_WIN32) || defined(WIN32)
  1186. #include <windows.h>
  1187. typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
  1188. DWORD CountSetBits(ULONG_PTR bitMask)
  1189. {
  1190. DWORD LSHIFT = sizeof(ULONG_PTR)*8 - 1;
  1191. DWORD bitSetCount = 0;
  1192. ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT;
  1193. DWORD i;
  1194. for (i = 0; i <= LSHIFT; ++i)
  1195. {
  1196. bitSetCount += ((bitMask & bitTest)?1:0);
  1197. bitTest/=2;
  1198. }
  1199. return bitSetCount;
  1200. }
  1201. int UTIL_countCores(int logical)
  1202. {
  1203. static int numCores = 0;
  1204. if (numCores != 0) return numCores;
  1205. { LPFN_GLPI glpi;
  1206. BOOL done = FALSE;
  1207. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
  1208. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
  1209. DWORD returnLength = 0;
  1210. size_t byteOffset = 0;
  1211. #if defined(_MSC_VER)
  1212. /* Visual Studio does not like the following cast */
  1213. # pragma warning( disable : 4054 ) /* conversion from function ptr to data ptr */
  1214. # pragma warning( disable : 4055 ) /* conversion from data ptr to function ptr */
  1215. #endif
  1216. glpi = (LPFN_GLPI)(void*)GetProcAddress(GetModuleHandle(TEXT("kernel32")),
  1217. "GetLogicalProcessorInformation");
  1218. if (glpi == NULL) {
  1219. goto failed;
  1220. }
  1221. while(!done) {
  1222. DWORD rc = glpi(buffer, &returnLength);
  1223. if (FALSE == rc) {
  1224. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1225. if (buffer)
  1226. free(buffer);
  1227. buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength);
  1228. if (buffer == NULL) {
  1229. perror("zstd");
  1230. exit(1);
  1231. }
  1232. } else {
  1233. /* some other error */
  1234. goto failed;
  1235. }
  1236. } else {
  1237. done = TRUE;
  1238. } }
  1239. ptr = buffer;
  1240. while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) {
  1241. if (ptr->Relationship == RelationProcessorCore) {
  1242. if (logical)
  1243. numCores += CountSetBits(ptr->ProcessorMask);
  1244. else
  1245. numCores++;
  1246. }
  1247. ptr++;
  1248. byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
  1249. }
  1250. free(buffer);
  1251. return numCores;
  1252. }
  1253. failed:
  1254. /* try to fall back on GetSystemInfo */
  1255. { SYSTEM_INFO sysinfo;
  1256. GetSystemInfo(&sysinfo);
  1257. numCores = sysinfo.dwNumberOfProcessors;
  1258. if (numCores == 0) numCores = 1; /* just in case */
  1259. }
  1260. return numCores;
  1261. }
  1262. #elif defined(__APPLE__)
  1263. #include <sys/sysctl.h>
  1264. /* Use apple-provided syscall
  1265. * see: man 3 sysctl */
  1266. int UTIL_countCores(int logical)
  1267. {
  1268. static S32 numCores = 0; /* apple specifies int32_t */
  1269. if (numCores != 0) return numCores;
  1270. { size_t size = sizeof(S32);
  1271. int const ret = sysctlbyname(logical ? "hw.logicalcpu" : "hw.physicalcpu", &numCores, &size, NULL, 0);
  1272. if (ret != 0) {
  1273. if (errno == ENOENT) {
  1274. /* entry not present, fall back on 1 */
  1275. numCores = 1;
  1276. } else {
  1277. perror("zstd: can't get number of cpus");
  1278. exit(1);
  1279. }
  1280. }
  1281. return numCores;
  1282. }
  1283. }
  1284. #elif defined(__linux__)
  1285. /* parse /proc/cpuinfo
  1286. * siblings / cpu cores should give hyperthreading ratio
  1287. * otherwise fall back on sysconf */
  1288. int UTIL_countCores(int logical)
  1289. {
  1290. static int numCores = 0;
  1291. if (numCores != 0) return numCores;
  1292. numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
  1293. if (numCores == -1) {
  1294. /* value not queryable, fall back on 1 */
  1295. return numCores = 1;
  1296. }
  1297. /* try to determine if there's hyperthreading */
  1298. { FILE* const cpuinfo = fopen("/proc/cpuinfo", "r");
  1299. #define BUF_SIZE 80
  1300. char buff[BUF_SIZE];
  1301. int siblings = 0;
  1302. int cpu_cores = 0;
  1303. int ratio = 1;
  1304. if (cpuinfo == NULL) {
  1305. /* fall back on the sysconf value */
  1306. return numCores;
  1307. }
  1308. /* assume the cpu cores/siblings values will be constant across all
  1309. * present processors */
  1310. while (!feof(cpuinfo)) {
  1311. if (fgets(buff, BUF_SIZE, cpuinfo) != NULL) {
  1312. if (strncmp(buff, "siblings", 8) == 0) {
  1313. const char* const sep = strchr(buff, ':');
  1314. if (sep == NULL || *sep == '\0') {
  1315. /* formatting was broken? */
  1316. goto failed;
  1317. }
  1318. siblings = atoi(sep + 1);
  1319. }
  1320. if (strncmp(buff, "cpu cores", 9) == 0) {
  1321. const char* const sep = strchr(buff, ':');
  1322. if (sep == NULL || *sep == '\0') {
  1323. /* formatting was broken? */
  1324. goto failed;
  1325. }
  1326. cpu_cores = atoi(sep + 1);
  1327. }
  1328. } else if (ferror(cpuinfo)) {
  1329. /* fall back on the sysconf value */
  1330. goto failed;
  1331. } }
  1332. if (siblings && cpu_cores && siblings > cpu_cores) {
  1333. ratio = siblings / cpu_cores;
  1334. }
  1335. if (ratio && numCores > ratio && !logical) {
  1336. numCores = numCores / ratio;
  1337. }
  1338. failed:
  1339. fclose(cpuinfo);
  1340. return numCores;
  1341. }
  1342. }
  1343. #elif defined(__FreeBSD__)
  1344. #include <sys/param.h>
  1345. #include <sys/sysctl.h>
  1346. /* Use physical core sysctl when available
  1347. * see: man 4 smp, man 3 sysctl */
  1348. int UTIL_countCores(int logical)
  1349. {
  1350. static int numCores = 0; /* freebsd sysctl is native int sized */
  1351. #if __FreeBSD_version >= 1300008
  1352. static int perCore = 1;
  1353. #endif
  1354. if (numCores != 0) return numCores;
  1355. #if __FreeBSD_version >= 1300008
  1356. { size_t size = sizeof(numCores);
  1357. int ret = sysctlbyname("kern.smp.cores", &numCores, &size, NULL, 0);
  1358. if (ret == 0) {
  1359. if (logical) {
  1360. ret = sysctlbyname("kern.smp.threads_per_core", &perCore, &size, NULL, 0);
  1361. /* default to physical cores if logical cannot be read */
  1362. if (ret == 0)
  1363. numCores *= perCore;
  1364. }
  1365. return numCores;
  1366. }
  1367. if (errno != ENOENT) {
  1368. perror("zstd: can't get number of cpus");
  1369. exit(1);
  1370. }
  1371. /* sysctl not present, fall through to older sysconf method */
  1372. }
  1373. #else
  1374. /* suppress unused parameter warning */
  1375. (void) logical;
  1376. #endif
  1377. numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
  1378. if (numCores == -1) {
  1379. /* value not queryable, fall back on 1 */
  1380. numCores = 1;
  1381. }
  1382. return numCores;
  1383. }
  1384. #elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__CYGWIN__)
  1385. /* Use POSIX sysconf
  1386. * see: man 3 sysconf */
  1387. int UTIL_countCores(int logical)
  1388. {
  1389. static int numCores = 0;
  1390. /* suppress unused parameter warning */
  1391. (void)logical;
  1392. if (numCores != 0) return numCores;
  1393. numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
  1394. if (numCores == -1) {
  1395. /* value not queryable, fall back on 1 */
  1396. return numCores = 1;
  1397. }
  1398. return numCores;
  1399. }
  1400. #else
  1401. int UTIL_countCores(int logical)
  1402. {
  1403. /* suppress unused parameter warning */
  1404. (void)logical;
  1405. /* assume 1 */
  1406. return 1;
  1407. }
  1408. #endif
  1409. int UTIL_countPhysicalCores(void)
  1410. {
  1411. return UTIL_countCores(0);
  1412. }
  1413. int UTIL_countLogicalCores(void)
  1414. {
  1415. return UTIL_countCores(1);
  1416. }
  1417. #if defined (__cplusplus)
  1418. }
  1419. #endif