forked from ccache/ccache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.c
1484 lines (1342 loc) · 27.5 KB
/
util.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2002 Andrew Tridgell
* Copyright (C) 2009-2013 Joel Rosdahl
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "ccache.h"
#include <zlib.h>
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef _WIN32
#include <windows.h>
#include <sys/locking.h>
#endif
static FILE *logfile;
static bool
init_log(void)
{
extern struct conf *conf;
if (logfile) {
return true;
}
assert(conf);
if (str_eq(conf->log_file, "")) {
return false;
}
logfile = fopen(conf->log_file, "a");
if (logfile) {
#ifndef _WIN32
int fd = fileno(logfile);
int flags = fcntl(fd, F_GETFD, 0);
if (flags >= 0) {
fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}
#endif
return true;
} else {
return false;
}
}
static void
log_prefix(bool log_updated_time)
{
#ifdef HAVE_GETTIMEOFDAY
char timestamp[100];
struct timeval tv;
struct tm *tm;
static char prefix[200];
if (log_updated_time) {
gettimeofday(&tv, NULL);
#ifdef __MINGW64_VERSION_MAJOR
tm = _localtime32(&tv.tv_sec);
#else
tm = localtime(&tv.tv_sec);
#endif
strftime(timestamp, sizeof(timestamp), "%Y-%m-%dT%H:%M:%S", tm);
snprintf(prefix, sizeof(prefix),
"[%s.%06d %-5d] ", timestamp, (int)tv.tv_usec, (int)getpid());
}
fputs(prefix, logfile);
#else
fprintf(logfile, "[%-5d] ", (int)getpid());
#endif
}
static long
path_max(const char *path)
{
#ifdef PATH_MAX
(void)path;
return PATH_MAX;
#elif defined(MAXPATHLEN)
(void)path;
return MAXPATHLEN;
#elif defined(_PC_PATH_MAX)
long maxlen = pathconf(path, _PC_PATH_MAX);
if (maxlen >= 4096) {
return maxlen;
} else {
return 4096;
}
#endif
}
static void
vlog(const char *format, va_list ap, bool log_updated_time)
{
if (!init_log()) {
return;
}
log_prefix(log_updated_time);
vfprintf(logfile, format, ap);
fprintf(logfile, "\n");
}
/*
* Write a message to the log file (adding a newline) and flush.
*/
void
cc_vlog(const char *format, va_list ap)
{
vlog(format, ap, true);
}
/*
* Write a message to the log file (adding a newline) and flush.
*/
void
cc_log(const char *format, ...)
{
va_list ap;
va_start(ap, format);
vlog(format, ap, true);
va_end(ap);
if (logfile) {
fflush(logfile);
}
}
/*
* Write a message to the log file (adding a newline) without flushing and with
* a reused timestamp.
*/
void
cc_bulklog(const char *format, ...)
{
va_list ap;
va_start(ap, format);
vlog(format, ap, false);
va_end(ap);
}
/*
* Log an executed command to the CCACHE_LOGFILE location.
*/
void
cc_log_argv(const char *prefix, char **argv)
{
if (!init_log()) {
return;
}
log_prefix(true);
fputs(prefix, logfile);
print_command(logfile, argv);
fflush(logfile);
}
/* something went badly wrong! */
void
fatal(const char *format, ...)
{
va_list ap;
char msg[1000];
va_start(ap, format);
vsnprintf(msg, sizeof(msg), format, ap);
va_end(ap);
cc_log("FATAL: %s", msg);
fprintf(stderr, "ccache: error: %s\n", msg);
exit(1);
}
/*
* Copy all data from fd_in to fd_out, decompressing data from fd_in if needed.
*/
void
copy_fd(int fd_in, int fd_out)
{
char buf[10240];
int n;
gzFile gz_in;
gz_in = gzdopen(dup(fd_in), "rb");
if (!gz_in) {
fatal("Failed to copy fd");
}
while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
ssize_t count, written = 0;
do {
count = write(fd_out, buf + written, n - written);
if (count == -1) {
if (errno != EAGAIN && errno != EINTR) {
fatal("Failed to copy fd");
}
} else {
written += count;
}
} while (written < n);
}
gzclose(gz_in);
}
#ifndef HAVE_MKSTEMP
/* cheap and nasty mkstemp replacement */
int
mkstemp(char *template)
{
mktemp(template);
return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
}
#endif
/*
* Copy src to dest, decompressing src if needed. compress_level > 0 decides
* whether dest will be compressed, and with which compression level.
*/
int
copy_file(const char *src, const char *dest, int compress_level)
{
int fd_in = -1, fd_out = -1;
gzFile gz_in = NULL, gz_out = NULL;
char buf[10240];
int n, written;
char *tmp_name;
#ifndef _WIN32
mode_t mask;
#endif
struct stat st;
int errnum;
tmp_name = format("%s.%s.XXXXXX", dest, tmp_string());
/* open destination file */
fd_out = mkstemp(tmp_name);
if (fd_out == -1) {
cc_log("mkstemp error: %s", strerror(errno));
goto error;
}
cc_log("Copying %s to %s via %s (%scompressed)",
src, dest, tmp_name, compress_level > 0 ? "" : "un");
/* open source file */
fd_in = open(src, O_RDONLY | O_BINARY);
if (fd_in == -1) {
cc_log("open error: %s", strerror(errno));
goto error;
}
gz_in = gzdopen(fd_in, "rb");
if (!gz_in) {
cc_log("gzdopen(src) error: %s", strerror(errno));
close(fd_in);
goto error;
}
if (compress_level > 0) {
/*
* A gzip file occupies at least 20 bytes, so it will always
* occupy an entire filesystem block, even for empty files.
* Turn off compression for empty files to save some space.
*/
if (fstat(fd_in, &st) != 0) {
cc_log("fstat error: %s", strerror(errno));
goto error;
}
if (file_size(&st) == 0) {
compress_level = 0;
}
}
if (compress_level > 0) {
gz_out = gzdopen(dup(fd_out), "wb");
if (!gz_out) {
cc_log("gzdopen(dest) error: %s", strerror(errno));
goto error;
}
gzsetparams(gz_out, compress_level, Z_DEFAULT_STRATEGY);
}
while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
if (compress_level > 0) {
written = gzwrite(gz_out, buf, n);
} else {
ssize_t count;
written = 0;
do {
count = write(fd_out, buf + written, n - written);
if (count == -1 && errno != EINTR) {
break;
}
written += count;
} while (written < n);
}
if (written != n) {
if (compress_level > 0) {
cc_log("gzwrite error: %s (errno: %s)",
gzerror(gz_in, &errnum),
strerror(errno));
} else {
cc_log("write error: %s", strerror(errno));
}
goto error;
}
}
/*
* gzeof won't tell if there's an error in the trailing CRC, so we must check
* gzerror before considering everything OK.
*/
gzerror(gz_in, &errnum);
if (!gzeof(gz_in) || (errnum != Z_OK && errnum != Z_STREAM_END)) {
cc_log("gzread error: %s (errno: %s)",
gzerror(gz_in, &errnum), strerror(errno));
gzclose(gz_in);
if (gz_out) {
gzclose(gz_out);
}
close(fd_out);
tmp_unlink(tmp_name);
free(tmp_name);
return -1;
}
gzclose(gz_in);
gz_in = NULL;
if (gz_out) {
gzclose(gz_out);
gz_out = NULL;
}
#ifndef _WIN32
/* get perms right on the tmp file */
mask = umask(0);
fchmod(fd_out, 0666 & ~mask);
umask(mask);
#endif
/* the close can fail on NFS if out of space */
if (close(fd_out) == -1) {
cc_log("close error: %s", strerror(errno));
goto error;
}
if (x_rename(tmp_name, dest) == -1) {
cc_log("rename error: %s", strerror(errno));
goto error;
}
free(tmp_name);
return 0;
error:
if (gz_in) {
gzclose(gz_in);
}
if (gz_out) {
gzclose(gz_out);
}
if (fd_out != -1) {
close(fd_out);
}
tmp_unlink(tmp_name);
free(tmp_name);
return -1;
}
/* Run copy_file() and, if successful, delete the source file. */
int
move_file(const char *src, const char *dest, int compress_level)
{
int ret;
ret = copy_file(src, dest, compress_level);
if (ret != -1) {
x_unlink(src);
}
return ret;
}
/*
* Like move_file(), but assumes that src is uncompressed and that src and dest
* are on the same file system.
*/
int
move_uncompressed_file(const char *src, const char *dest, int compress_level)
{
if (compress_level > 0) {
return move_file(src, dest, compress_level);
} else {
return x_rename(src, dest);
}
}
/* test if a file is zlib compressed */
bool
file_is_compressed(const char *filename)
{
FILE *f;
f = fopen(filename, "rb");
if (!f) {
return false;
}
/* test if file starts with 1F8B, which is zlib's
* magic number */
if ((fgetc(f) != 0x1f) || (fgetc(f) != 0x8b)) {
fclose(f);
return false;
}
fclose(f);
return true;
}
/* make sure a directory exists */
int
create_dir(const char *dir)
{
struct stat st;
if (stat(dir, &st) == 0) {
if (S_ISDIR(st.st_mode)) {
return 0;
}
errno = ENOTDIR;
return 1;
}
if (mkdir(dir, 0777) != 0 && errno != EEXIST) {
return 1;
}
return 0;
}
/* Create directories leading to path. Returns 0 on success, otherwise -1. */
int
create_parent_dirs(const char *path)
{
struct stat st;
int res;
char *parent = dirname(path);
if (stat(parent, &st) == 0) {
if (S_ISDIR(st.st_mode)) {
res = 0;
} else {
res = -1;
errno = ENOTDIR;
}
} else {
res = create_parent_dirs(parent);
if (res == 0) {
res = mkdir(parent, 0777);
/* Have to handle the condition of the directory already existing because
* the file system could have changed in between calling stat and
* actually creating the directory. This can happen when there are
* multiple instances of ccache running and trying to create the same
* directory chain, which usually is the case when the cache root does
* not initially exist. As long as one of the processes creates the
* directories then our condition is satisfied and we avoid a race
* condition.
*/
if (res != 0 && errno == EEXIST) {
res = 0;
}
} else {
res = -1;
}
}
free(parent);
return res;
}
/*
* Return a static string with the current hostname.
*/
const char *
get_hostname(void)
{
static char hostname[200] = "";
if (!hostname[0]) {
strcpy(hostname, "unknown");
#if HAVE_GETHOSTNAME
gethostname(hostname, sizeof(hostname)-1);
#endif
hostname[sizeof(hostname)-1] = 0;
}
return hostname;
}
/*
* Return a string to be used to distinguish temporary files. Also tries to
* cope with NFS by adding the local hostname.
*/
const char *
tmp_string(void)
{
static char *ret;
if (!ret) {
ret = format("%s.%u", get_hostname(), (unsigned)getpid());
}
return ret;
}
/*
* Return the hash result as a hex string. Size -1 means don't include size
* suffix. Caller frees.
*/
char *
format_hash_as_string(const unsigned char *hash, int size)
{
char *ret;
int i;
ret = x_malloc(53);
for (i = 0; i < 16; i++) {
sprintf(&ret[i*2], "%02x", (unsigned) hash[i]);
}
if (size >= 0) {
sprintf(&ret[i*2], "-%u", size);
}
return ret;
}
char const CACHEDIR_TAG[] =
"Signature: 8a477f597d28d172789f06886806bc55\n"
"# This file is a cache directory tag created by ccache.\n"
"# For information about cache directory tags, see:\n"
"# http://www.brynosaurus.com/cachedir/\n";
int
create_cachedirtag(const char *dir)
{
struct stat st;
FILE *f;
char *filename = format("%s/CACHEDIR.TAG", dir);
if (stat(filename, &st) == 0) {
if (S_ISREG(st.st_mode)) {
goto success;
}
errno = EEXIST;
goto error;
}
f = fopen(filename, "w");
if (!f) goto error;
if (fwrite(CACHEDIR_TAG, sizeof(CACHEDIR_TAG)-1, 1, f) != 1) {
fclose(f);
goto error;
}
if (fclose(f)) goto error;
success:
free(filename);
return 0;
error:
free(filename);
return 1;
}
/* Construct a string according to a format. Caller frees. */
char *
format(const char *format, ...)
{
va_list ap;
char *ptr = NULL;
va_start(ap, format);
if (vasprintf(&ptr, format, ap) == -1) {
fatal("Out of memory in format");
}
va_end(ap);
if (!*ptr) fatal("Internal error in format");
return ptr;
}
/*
this is like strdup() but dies if the malloc fails
*/
char *
x_strdup(const char *s)
{
char *ret;
ret = strdup(s);
if (!ret) {
fatal("Out of memory in x_strdup");
}
return ret;
}
/*
this is like strndup() but dies if the malloc fails
*/
char *
x_strndup(const char *s, size_t n)
{
char *ret;
#ifndef HAVE_STRNDUP
size_t m;
if (!s)
return NULL;
m = 0;
while (m < n && s[m]) {
m++;
}
ret = malloc(m + 1);
if (ret) {
memcpy(ret, s, m);
ret[m] = '\0';
}
#else
ret = strndup(s, n);
#endif
if (!ret) {
fatal("x_strndup: Could not allocate %lu bytes", (unsigned long)n);
}
return ret;
}
/*
this is like malloc() but dies if the malloc fails
*/
void *
x_malloc(size_t size)
{
void *ret;
if (size == 0) {
/*
* malloc() may return NULL if size is zero, so always do this to make sure
* that the code handles it regardless of platform.
*/
return NULL;
}
ret = malloc(size);
if (!ret) {
fatal("x_malloc: Could not allocate %lu bytes", (unsigned long)size);
}
return ret;
}
/* This is like calloc() but dies if the allocation fails. */
void *
x_calloc(size_t nmemb, size_t size)
{
void *ret;
if (nmemb * size == 0) {
/*
* calloc() may return NULL if nmemb or size is 0, so always do this to
* make sure that the code handles it regardless of platform.
*/
return NULL;
}
ret = calloc(nmemb, size);
if (!ret) {
fatal("x_calloc: Could not allocate %lu bytes", (unsigned long)size);
}
return ret;
}
/*
this is like realloc() but dies if the malloc fails
*/
void *
x_realloc(void *ptr, size_t size)
{
void *p2;
if (!ptr) return x_malloc(size);
p2 = realloc(ptr, size);
if (!p2) {
fatal("x_realloc: Could not allocate %lu bytes", (unsigned long)size);
}
return p2;
}
/* This is like unsetenv. */
void x_unsetenv(const char *name)
{
#ifdef HAVE_UNSETENV
unsetenv(name);
#else
putenv(x_strdup(name)); /* Leak to environment. */
#endif
}
/*
* Construct a string according to the format and store it in *ptr. The
* original *ptr is then freed.
*/
void
reformat(char **ptr, const char *format, ...)
{
char *saved = *ptr;
va_list ap;
*ptr = NULL;
va_start(ap, format);
if (vasprintf(ptr, format, ap) == -1) {
fatal("Out of memory in reformat");
}
va_end(ap);
if (!ptr) fatal("Out of memory in reformat");
if (saved) {
free(saved);
}
}
/*
* Recursive directory traversal. fn() is called on all entries in the tree.
*/
void
traverse(const char *dir, void (*fn)(const char *, struct stat *))
{
DIR *d;
struct dirent *de;
d = opendir(dir);
if (!d) return;
while ((de = readdir(d))) {
char *fname;
struct stat st;
if (str_eq(de->d_name, ".")) continue;
if (str_eq(de->d_name, "..")) continue;
if (strlen(de->d_name) == 0) continue;
fname = format("%s/%s", dir, de->d_name);
if (lstat(fname, &st)) {
if (errno != ENOENT) {
perror(fname);
}
free(fname);
continue;
}
if (S_ISDIR(st.st_mode)) {
traverse(fname, fn);
}
fn(fname, &st);
free(fname);
}
closedir(d);
}
/* return the base name of a file - caller frees */
char *
basename(const char *path)
{
char *p;
p = strrchr(path, '/');
if (p) path = p + 1;
#ifdef _WIN32
p = strrchr(path, '\\');
if (p) path = p + 1;
#endif
return x_strdup(path);
}
/* return the dir name of a file - caller frees */
char *
dirname(const char *path)
{
char *p;
char *p2 = NULL;
char *s;
s = x_strdup(path);
p = strrchr(s, '/');
#ifdef _WIN32
p2 = strrchr(s, '\\');
#endif
if (p < p2)
p = p2;
if (p) {
*p = 0;
return s;
} else {
free(s);
return x_strdup(".");
}
}
/*
* Return the file extension (including the dot) of a path as a pointer into
* path. If path has no file extension, the empty string and the end of path is
* returned.
*/
const char *
get_extension(const char *path)
{
size_t len = strlen(path);
const char *p;
for (p = &path[len - 1]; p >= path; --p) {
if (*p == '.') {
return p;
}
if (*p == '/') {
break;
}
}
return &path[len];
}
/*
* Return a string containing the given path without the filename extension.
* Caller frees.
*/
char *
remove_extension(const char *path)
{
return x_strndup(path, strlen(path) - strlen(get_extension(path)));
}
/* return size on disk of a file */
size_t
file_size(struct stat *st)
{
#ifdef _WIN32
return (st->st_size + 1023) & ~1023;
#else
size_t size = st->st_blocks * 512;
if ((size_t)st->st_size > size) {
/* probably a broken stat() call ... */
size = (st->st_size + 1023) & ~1023;
}
return size;
#endif
}
/*
* Create a file for writing. Creates parent directories if they don't exist.
*/
int
safe_create_wronly(const char *fname)
{
int fd = open(fname, O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0666);
if (fd == -1 && errno == ENOENT) {
/*
* Only make sure parent directories exist when have failed to open the
* file -- this saves stat() calls.
*/
if (create_parent_dirs(fname) == 0) {
fd = open(fname, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0666);
}
}
return fd;
}
/* Format a size as a human-readable string. Caller frees. */
char *
format_human_readable_size(uint64_t v)
{
char *s;
if (v >= 1000*1000*1000) {
s = format("%.1f GB", v/((double)(1000*1000*1000)));
} else if (v >= 1000*1000) {
s = format("%.1f MB", v/((double)(1000*1000)));
} else {
s = format("%.1f kB", v/((double)(1000)));
}
return s;
}
/* Format a size as a parsable string. Caller frees. */
char *
format_parsable_size_with_suffix(uint64_t size)
{
char *s;
if (size >= 1000*1000*1000) {
s = format("%.1fG", size / ((double)(1000*1000*1000)));
} else if (size >= 1000*1000) {
s = format("%.1fM", size / ((double)(1000*1000)));
} else if (size >= 1000) {
s = format("%.1fk", size / ((double)(1000)));
} else {
s = format("%u", (unsigned)size);
}
return s;
}
/*
* Parse a "size value", i.e. a string that can end in k, M, G, T (10-based
* suffixes) or Ki, Mi, Gi, Ti (2-based suffixes). For backward compatibility,
* K is also recognized as a synonym of k.
*/
bool
parse_size_with_suffix(const char *str, uint64_t *size)
{
char *p;
double x;
errno = 0;
x = strtod(str, &p);
if (errno != 0 || x < 0 || p == str || *str == '\0') {
return false;
}
while (isspace(*p)) {
++p;
}
if (*p != '\0') {
unsigned multiplier;
if (*(p+1) == 'i') {
multiplier = 1024;
} else {
multiplier = 1000;
}
switch (*p) {
case 'T':
x *= multiplier;
case 'G':
x *= multiplier;
case 'M':
x *= multiplier;
case 'K':
case 'k':
x *= multiplier;
break;
default:
return false;
}
}
*size = x;
return true;
}
/*
a sane realpath() function, trying to cope with stupid path limits and
a broken API
*/
char *
x_realpath(const char *path)
{
long maxlen = path_max(path);
char *ret, *p;
#ifdef _WIN32
HANDLE path_handle;
#endif
ret = x_malloc(maxlen);
#if HAVE_REALPATH
p = realpath(path, ret);
#elif defined(_WIN32)
path_handle = CreateFile(
path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
GetFinalPathNameByHandle(path_handle, ret, maxlen, FILE_NAME_NORMALIZED);
CloseHandle(path_handle);
p = ret+4;// strip the \\?\ from the file name
#else
/* yes, there are such systems. This replacement relies on
the fact that when we call x_realpath we only care about symlinks */
{
int len = readlink(path, ret, maxlen-1);
if (len == -1) {
free(ret);
return NULL;
}
ret[len] = 0;
p = ret;
}
#endif
if (p) {