util.c 49 KB

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