util.c 49 KB

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