-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSystemTools.cxx
5053 lines (4550 loc) · 139 KB
/
SystemTools.cxx
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
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#ifdef __osf__
# define _OSF_SOURCE
# define _POSIX_C_SOURCE 199506L
# define _XOPEN_SOURCE_EXTENDED
#endif
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__MINGW32__))
# define KWSYS_WINDOWS_DIRS
#else
# if defined(__SUNPRO_CC)
# include <fcntl.h>
# endif
#endif
#if defined(_WIN32) && !defined(_WIN32_WINNT)
# define _WIN32_WINNT _WIN32_WINNT_VISTA
#endif
#include "kwsysPrivate.h"
#include KWSYS_HEADER(RegularExpression.hxx)
#include KWSYS_HEADER(SystemTools.hxx)
#include KWSYS_HEADER(Directory.hxx)
#include KWSYS_HEADER(FStream.hxx)
#include KWSYS_HEADER(Encoding.h)
#include KWSYS_HEADER(Encoding.hxx)
#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <utility>
#include <vector>
#ifdef _WIN32
# include <cwchar>
# include <unordered_map>
#endif
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "Directory.hxx.in"
# include "Encoding.hxx.in"
# include "FStream.hxx.in"
# include "RegularExpression.hxx.in"
# include "SystemTools.hxx.in"
#endif
#ifdef _MSC_VER
# pragma warning(disable : 4786)
#endif
#if defined(__sgi) && !defined(__GNUC__)
# pragma set woff 1375 /* base class destructor not virtual */
#endif
#include <cctype>
#include <cerrno>
#ifdef __QNX__
# include <malloc.h> /* for malloc/free on QNX */
#endif
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if defined(_WIN32) && !defined(_MSC_VER) && defined(__GNUC__)
# include <strings.h> /* for strcasecmp */
#endif
#ifdef _MSC_VER
# define umask _umask
#endif
// support for realpath call
#ifndef _WIN32
# include <climits>
# include <pwd.h>
# include <sys/ioctl.h>
# include <sys/time.h>
# include <sys/wait.h>
# include <unistd.h>
# include <utime.h>
# ifndef __VMS
# include <sys/param.h>
# include <termios.h>
# endif
# include <csignal> /* sigprocmask */
#endif
#ifdef __linux
# include <linux/fs.h>
#endif
#if defined(__APPLE__) && \
(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ - 0 >= 101200)
# define KWSYS_SYSTEMTOOLS_HAVE_MACOS_COPYFILE_CLONE
# include <copyfile.h>
# include <sys/stat.h>
#endif
// Windows API.
#if defined(_WIN32)
# include <windows.h>
# include <winioctl.h>
# ifndef INVALID_FILE_ATTRIBUTES
# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
# endif
# ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
# define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
# endif
# if defined(_MSC_VER) && _MSC_VER >= 1800
# define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
# endif
# ifndef IO_REPARSE_TAG_APPEXECLINK
# define IO_REPARSE_TAG_APPEXECLINK (0x8000001BL)
# endif
// from ntifs.h, which can only be used by drivers
typedef struct _REPARSE_DATA_BUFFER
{
ULONG ReparseTag;
USHORT ReparseDataLength;
USHORT Reserved;
union
{
struct
{
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
ULONG Flags;
WCHAR PathBuffer[1];
} SymbolicLinkReparseBuffer;
struct
{
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
WCHAR PathBuffer[1];
} MountPointReparseBuffer;
struct
{
UCHAR DataBuffer[1];
} GenericReparseBuffer;
struct
{
ULONG Version;
WCHAR StringList[1];
// In version 3, there are 4 NUL-terminated strings:
// * Package ID
// * Entry Point
// * Executable Path
// * Application Type
} AppExecLinkReparseBuffer;
} DUMMYUNIONNAME;
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
namespace {
WCHAR* GetAppExecLink(PREPARSE_DATA_BUFFER data, size_t& len)
{
// We only know the layout of version 3.
if (data->AppExecLinkReparseBuffer.Version != 3) {
return nullptr;
}
WCHAR* pstr = data->AppExecLinkReparseBuffer.StringList;
// Skip the package id and entry point strings.
for (int i = 0; i < 2; ++i) {
len = std::wcslen(pstr);
if (len == 0) {
return nullptr;
}
pstr += len + 1;
}
// The third string is the executable path.
len = std::wcslen(pstr);
if (len == 0) {
return nullptr;
}
return pstr;
}
}
#endif
#if !KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
extern char** environ;
#endif
// getpwnam doesn't exist on Windows and Cray Xt3/Catamount
// same for TIOCGWINSZ
#if defined(_WIN32) || defined(__LIBCATAMOUNT__) || \
(defined(HAVE_GETPWNAM) && HAVE_GETPWNAM == 0)
# undef HAVE_GETPWNAM
# undef HAVE_TTY_INFO
#else
# define HAVE_GETPWNAM 1
# define HAVE_TTY_INFO 1
#endif
#define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)"
#define VTK_URL_REGEX \
"([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]*)(:([0-9]+))?/" \
"(.+)?"
#define VTK_URL_BYTE_REGEX "%[0-9a-fA-F][0-9a-fA-F]"
#ifdef _MSC_VER
# include <sys/utime.h>
#else
# include <utime.h>
#endif
// This is a hack to prevent warnings about these functions being
// declared but not referenced.
#if defined(__sgi) && !defined(__GNUC__)
# include <sys/termios.h>
namespace KWSYS_NAMESPACE {
class SystemToolsHack
{
public:
enum
{
Ref1 = sizeof(cfgetospeed(0)),
Ref2 = sizeof(cfgetispeed(0)),
Ref3 = sizeof(tcgetattr(0, 0)),
Ref4 = sizeof(tcsetattr(0, 0, 0)),
Ref5 = sizeof(cfsetospeed(0, 0)),
Ref6 = sizeof(cfsetispeed(0, 0))
};
};
}
#endif
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__MINGW32__))
# include <direct.h>
# include <io.h>
# define _unlink unlink
#endif
/* The maximum length of a file name. */
#if defined(PATH_MAX)
# define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
#elif defined(MAXPATHLEN)
# define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
#else
# define KWSYS_SYSTEMTOOLS_MAXPATH 16384
#endif
#if defined(__BEOS__) && !defined(__ZETA__)
# include <be/kernel/OS.h>
# include <be/storage/Path.h>
// BeOS 5 doesn't have usleep(), but it has snooze(), which is identical.
static inline void usleep(unsigned int msec)
{
::snooze(msec);
}
// BeOS 5 also doesn't have realpath(), but its C++ API offers something close.
static inline char* realpath(const char* path, char* resolved_path)
{
const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH;
snprintf(resolved_path, maxlen, "%s", path);
BPath normalized(resolved_path, nullptr, true);
const char* resolved = normalized.Path();
if (resolved != nullptr) // nullptr == No such file.
{
if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen) {
return resolved_path;
}
}
return nullptr; // something went wrong.
}
#endif
#ifdef _WIN32
static time_t windows_filetime_to_posix_time(const FILETIME& ft)
{
LARGE_INTEGER date;
date.HighPart = ft.dwHighDateTime;
date.LowPart = ft.dwLowDateTime;
// removes the diff between 1970 and 1601
date.QuadPart -= ((LONGLONG)(369 * 365 + 89) * 24 * 3600 * 10000000);
// converts back from 100-nanoseconds to seconds
return date.QuadPart / 10000000;
}
#endif
#ifdef KWSYS_WINDOWS_DIRS
# include <wctype.h>
# ifdef _MSC_VER
typedef KWSYS_NAMESPACE::SystemTools::mode_t mode_t;
# endif
inline int Mkdir(const std::string& dir, const mode_t* mode)
{
int ret =
_wmkdir(KWSYS_NAMESPACE::Encoding::ToWindowsExtendedPath(dir).c_str());
if (ret == 0 && mode)
KWSYS_NAMESPACE::SystemTools::SetPermissions(dir, *mode);
return ret;
}
inline int Rmdir(const std::string& dir)
{
return _wrmdir(
KWSYS_NAMESPACE::Encoding::ToWindowsExtendedPath(dir).c_str());
}
inline const char* Getcwd(char* buf, unsigned int len)
{
std::vector<wchar_t> w_buf(len);
if (_wgetcwd(&w_buf[0], len)) {
size_t nlen = kwsysEncoding_wcstombs(buf, &w_buf[0], len);
if (nlen == static_cast<size_t>(-1)) {
return 0;
}
if (nlen < len) {
// make sure the drive letter is capital
if (nlen > 1 && buf[1] == ':') {
buf[0] = toupper(buf[0]);
}
return buf;
}
}
return 0;
}
inline int Chdir(const std::string& dir)
{
return _wchdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
}
inline void Realpath(const std::string& path, std::string& resolved_path,
std::string* errorMessage = nullptr)
{
std::wstring tmp = KWSYS_NAMESPACE::Encoding::ToWide(path);
wchar_t* ptemp;
wchar_t fullpath[MAX_PATH];
DWORD bufferLen = GetFullPathNameW(
tmp.c_str(), sizeof(fullpath) / sizeof(fullpath[0]), fullpath, &ptemp);
if (bufferLen < sizeof(fullpath) / sizeof(fullpath[0])) {
resolved_path = KWSYS_NAMESPACE::Encoding::ToNarrow(fullpath);
KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
} else if (errorMessage) {
if (bufferLen) {
*errorMessage = "Destination path buffer size too small.";
} else if (unsigned int errorId = GetLastError()) {
LPSTR message = nullptr;
DWORD size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, errorId, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&message, 0, nullptr);
*errorMessage = std::string(message, size);
LocalFree(message);
} else {
*errorMessage = "Unknown error.";
}
resolved_path = "";
} else {
resolved_path = path;
}
}
#else
# include <sys/types.h>
# include <fcntl.h>
# include <unistd.h>
inline int Mkdir(const std::string& dir, const mode_t* mode)
{
return mkdir(dir.c_str(), mode ? *mode : 00777);
}
inline int Rmdir(const std::string& dir)
{
return rmdir(dir.c_str());
}
inline const char* Getcwd(char* buf, unsigned int len)
{
return getcwd(buf, len);
}
inline int Chdir(const std::string& dir)
{
return chdir(dir.c_str());
}
inline void Realpath(const std::string& path, std::string& resolved_path,
std::string* errorMessage = nullptr)
{
char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
errno = 0;
char* ret = realpath(path.c_str(), resolved_name);
if (ret) {
resolved_path = ret;
} else if (errorMessage) {
if (errno) {
*errorMessage = strerror(errno);
} else {
*errorMessage = "Unknown error.";
}
resolved_path = "";
} else {
// if path resolution fails, return what was passed in
resolved_path = path;
}
}
#endif
namespace KWSYS_NAMESPACE {
double SystemTools::GetTime()
{
#if defined(_WIN32) && !defined(__CYGWIN__)
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
return (429.4967296 * ft.dwHighDateTime + 0.0000001 * ft.dwLowDateTime -
11644473600.0);
#else
struct timeval t;
gettimeofday(&t, nullptr);
return 1.0 * double(t.tv_sec) + 0.000001 * double(t.tv_usec);
#endif
}
/* Type of character storing the environment. */
#if defined(_WIN32)
typedef wchar_t envchar;
#else
using envchar = char;
#endif
/* Order by environment key only (VAR from VAR=VALUE). */
struct kwsysEnvCompare
{
bool operator()(const envchar* l, const envchar* r) const
{
#if defined(_WIN32)
const wchar_t* leq = wcschr(l, L'=');
const wchar_t* req = wcschr(r, L'=');
size_t llen = leq ? (leq - l) : wcslen(l);
size_t rlen = req ? (req - r) : wcslen(r);
if (llen == rlen) {
return wcsncmp(l, r, llen) < 0;
} else {
return wcscmp(l, r) < 0;
}
#else
const char* leq = strchr(l, '=');
const char* req = strchr(r, '=');
size_t llen = leq ? static_cast<size_t>(leq - l) : strlen(l);
size_t rlen = req ? static_cast<size_t>(req - r) : strlen(r);
if (llen == rlen) {
return strncmp(l, r, llen) < 0;
} else {
return strcmp(l, r) < 0;
}
#endif
}
};
class kwsysEnvSet : public std::set<const envchar*, kwsysEnvCompare>
{
public:
class Free
{
const envchar* Env;
public:
Free(const envchar* env)
: Env(env)
{
}
~Free() { free(const_cast<envchar*>(this->Env)); }
Free(const Free&) = delete;
Free& operator=(const Free&) = delete;
};
const envchar* Release(const envchar* env)
{
const envchar* old = nullptr;
auto i = this->find(env);
if (i != this->end()) {
old = *i;
this->erase(i);
}
return old;
}
};
#ifdef _WIN32
# if defined(_WIN64)
static constexpr size_t FNV_OFFSET_BASIS = 14695981039346656037ULL;
static constexpr size_t FNV_PRIME = 1099511628211ULL;
# else
static constexpr size_t FNV_OFFSET_BASIS = 2166136261U;
static constexpr size_t FNV_PRIME = 16777619U;
# endif
// Case insensitive Fnv1a hash
struct SystemToolsPathCaseHash
{
size_t operator()(std::string const& path) const
{
size_t hash = FNV_OFFSET_BASIS;
for (auto c : path) {
hash ^= static_cast<size_t>(std::tolower(c));
hash *= FNV_PRIME;
}
return hash;
}
};
struct SystemToolsPathCaseEqual
{
bool operator()(std::string const& l, std::string const& r) const
{
# ifdef _MSC_VER
return _stricmp(l.c_str(), r.c_str()) == 0;
# elif defined(__GNUC__)
return strcasecmp(l.c_str(), r.c_str()) == 0;
# else
return SystemTools::Strucmp(l.c_str(), r.c_str()) == 0;
# endif
}
};
#endif
/**
* SystemTools static variables singleton class.
*/
class SystemToolsStatic
{
public:
using StringMap = std::map<std::string, std::string>;
#if KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP
/**
* Path translation table from dir to refdir
* Each time 'dir' will be found it will be replace by 'refdir'
*/
StringMap TranslationMap;
#endif
#ifdef _WIN32
static std::string GetCasePathName(std::string const& pathIn,
bool const cache);
static std::string GetActualCaseForPathCached(std::string const& path);
static const char* GetEnvBuffered(const char* key);
std::unordered_map<std::string, std::string, SystemToolsPathCaseHash,
SystemToolsPathCaseEqual>
FindFileMap;
std::unordered_map<std::string, std::string, SystemToolsPathCaseHash,
SystemToolsPathCaseEqual>
PathCaseMap;
std::map<std::string, std::string> EnvMap;
#endif
#ifdef __CYGWIN__
StringMap Cyg2Win32Map;
#endif
/**
* Actual implementation of ReplaceString.
*/
static void ReplaceString(std::string& source, const char* replace,
size_t replaceSize, const std::string& with);
/**
* Actual implementation of FileIsFullPath.
*/
static bool FileIsFullPath(const char*, size_t);
/**
* Find a filename (file or directory) in the system PATH, with
* optional extra paths.
*/
static std::string FindName(
const std::string& name,
const std::vector<std::string>& userPaths = std::vector<std::string>(),
bool no_system_path = false);
};
// Do NOT initialize. Default initialization to zero is necessary.
static SystemToolsStatic* SystemToolsStatics;
#ifdef _WIN32
std::string SystemToolsStatic::GetCasePathName(std::string const& pathIn,
bool const cache)
{
std::string casePath;
// First check if the file is relative. We don't fix relative paths since the
// real case depends on the root directory and the given path fragment may
// have meaning elsewhere in the project.
if (!SystemTools::FileIsFullPath(pathIn)) {
// This looks unnecessary, but it allows for the return value optimization
// since all return paths return the same local variable.
casePath = pathIn;
return casePath;
}
std::vector<std::string> path_components;
SystemTools::SplitPath(pathIn, path_components);
// Start with root component.
std::vector<std::string>::size_type idx = 0;
casePath = path_components[idx++];
// make sure drive letter is always upper case
if (casePath.size() > 1 && casePath[1] == ':') {
casePath[0] = toupper(casePath[0]);
}
const char* sep = "";
// If network path, fill casePath with server/share so FindFirstFile
// will work after that. Maybe someday call other APIs to get
// actual case of servers and shares.
if (path_components.size() > 2 && path_components[0] == "//") {
casePath += path_components[idx++];
casePath += "/";
casePath += path_components[idx++];
sep = "/";
}
// Convert case of all components that exist.
bool converting = true;
for (; idx < path_components.size(); idx++) {
casePath += sep;
sep = "/";
if (converting) {
// If path component contains wildcards, we skip matching
// because these filenames are not allowed on windows,
// and we do not want to match a different file.
if (path_components[idx].find('*') != std::string::npos ||
path_components[idx].find('?') != std::string::npos) {
converting = false;
} else {
std::string test_str = casePath;
test_str += path_components[idx];
bool found_in_cache = false;
if (cache) {
auto const it = SystemToolsStatics->FindFileMap.find(test_str);
if (it != SystemToolsStatics->FindFileMap.end()) {
path_components[idx] = it->second;
found_in_cache = true;
}
}
if (!found_in_cache) {
WIN32_FIND_DATAW findData;
HANDLE hFind =
::FindFirstFileW(Encoding::ToWide(test_str).c_str(), &findData);
if (INVALID_HANDLE_VALUE != hFind) {
auto case_file_name = Encoding::ToNarrow(findData.cFileName);
if (cache) {
SystemToolsStatics->FindFileMap.emplace(test_str,
case_file_name);
}
path_components[idx] = std::move(case_file_name);
::FindClose(hFind);
} else {
converting = false;
}
}
}
}
casePath += path_components[idx];
}
return casePath;
}
std::string SystemToolsStatic::GetActualCaseForPathCached(std::string const& p)
{
std::string casePath;
auto it = SystemToolsStatics->PathCaseMap.find(p);
if (it != SystemToolsStatics->PathCaseMap.end()) {
casePath = it->second;
} else {
casePath = SystemToolsStatic::GetCasePathName(p, true);
SystemToolsStatics->PathCaseMap.emplace(p, casePath);
}
return casePath;
}
#endif
// adds the elements of the env variable path to the arg passed in
void SystemTools::GetPath(std::vector<std::string>& path, const char* env)
{
size_t const old_size = path.size();
#if defined(_WIN32) && !defined(__CYGWIN__)
const char pathSep = ';';
#else
const char pathSep = ':';
#endif
if (!env) {
env = "PATH";
}
std::string pathEnv;
if (!SystemTools::GetEnv(env, pathEnv)) {
return;
}
// A hack to make the below algorithm work.
if (!pathEnv.empty() && pathEnv.back() != pathSep) {
pathEnv += pathSep;
}
std::string::size_type start = 0;
bool done = false;
while (!done) {
std::string::size_type endpos = pathEnv.find(pathSep, start);
if (endpos != std::string::npos) {
path.push_back(pathEnv.substr(start, endpos - start));
start = endpos + 1;
} else {
done = true;
}
}
for (auto i = path.begin() + old_size; i != path.end(); ++i) {
SystemTools::ConvertToUnixSlashes(*i);
}
}
#if defined(_WIN32)
const char* SystemToolsStatic::GetEnvBuffered(const char* key)
{
std::string env;
if (SystemTools::GetEnv(key, env)) {
std::string& menv = SystemToolsStatics->EnvMap[key];
if (menv != env) {
menv = std::move(env);
}
return menv.c_str();
}
return nullptr;
}
#endif
const char* SystemTools::GetEnv(const char* key)
{
#if defined(_WIN32)
return SystemToolsStatic::GetEnvBuffered(key);
#else
return getenv(key);
#endif
}
const char* SystemTools::GetEnv(const std::string& key)
{
#if defined(_WIN32)
return SystemToolsStatic::GetEnvBuffered(key.c_str());
#else
return getenv(key.c_str());
#endif
}
bool SystemTools::GetEnv(const char* key, std::string& result)
{
#if defined(_WIN32)
auto wide_key = Encoding::ToWide(key);
auto result_size = GetEnvironmentVariableW(wide_key.data(), nullptr, 0);
if (result_size <= 0) {
return false;
}
std::wstring wide_result;
wide_result.resize(result_size - 1);
GetEnvironmentVariableW(wide_key.data(), &wide_result[0], result_size);
result = Encoding::ToNarrow(wide_result);
return true;
#else
const char* v = getenv(key);
if (v) {
result = v;
return true;
}
#endif
return false;
}
bool SystemTools::GetEnv(const std::string& key, std::string& result)
{
return SystemTools::GetEnv(key.c_str(), result);
}
bool SystemTools::HasEnv(const char* key)
{
#if defined(_WIN32)
const std::wstring wkey = Encoding::ToWide(key);
const wchar_t* v = _wgetenv(wkey.c_str());
#else
const char* v = getenv(key);
#endif
return v != nullptr;
}
bool SystemTools::HasEnv(const std::string& key)
{
return SystemTools::HasEnv(key.c_str());
}
#if KWSYS_CXX_HAS_UNSETENV
/* unsetenv("A") removes A from the environment.
On older platforms it returns void instead of int. */
static int kwsysUnPutEnv(const std::string& env)
{
size_t pos = env.find('=');
if (pos != std::string::npos) {
std::string name = env.substr(0, pos);
unsetenv(name.c_str());
} else {
unsetenv(env.c_str());
}
return 0;
}
#elif defined(__CYGWIN__) || defined(__GLIBC__)
/* putenv("A") removes A from the environment. It must not put the
memory in the environment because it does not have any "=" syntax. */
static int kwsysUnPutEnv(const std::string& env)
{
int err = 0;
size_t pos = env.find('=');
size_t const len = pos == std::string::npos ? env.size() : pos;
size_t const sz = len + 1;
char local_buf[256];
char* buf = sz > sizeof(local_buf) ? (char*)malloc(sz) : local_buf;
if (!buf) {
return -1;
}
strncpy(buf, env.c_str(), len);
buf[len] = 0;
if (putenv(buf) < 0 && errno != EINVAL) {
err = errno;
}
if (buf != local_buf) {
free(buf);
}
if (err) {
errno = err;
return -1;
}
return 0;
}
#elif defined(_WIN32)
/* putenv("A=") places "A=" in the environment, which is as close to
removal as we can get with the putenv API. We have to leak the
most recent value placed in the environment for each variable name
on program exit in case exit routines access it. */
static kwsysEnvSet kwsysUnPutEnvSet;
static int kwsysUnPutEnv(std::string const& env)
{
std::wstring wEnv = Encoding::ToWide(env);
size_t const pos = wEnv.find('=');
size_t const len = pos == std::string::npos ? wEnv.size() : pos;
wEnv.resize(len + 1, L'=');
wchar_t* newEnv = _wcsdup(wEnv.c_str());
if (!newEnv) {
return -1;
}
kwsysEnvSet::Free oldEnv(kwsysUnPutEnvSet.Release(newEnv));
kwsysUnPutEnvSet.insert(newEnv);
return _wputenv(newEnv);
}
#else
/* Manipulate the "environ" global directly. */
static int kwsysUnPutEnv(const std::string& env)
{
size_t pos = env.find('=');
size_t const len = pos == std::string::npos ? env.size() : pos;
int in = 0;
int out = 0;
while (environ[in]) {
if (strlen(environ[in]) > len && environ[in][len] == '=' &&
strncmp(env.c_str(), environ[in], len) == 0) {
++in;
} else {
environ[out++] = environ[in++];
}
}
while (out < in) {
environ[out++] = 0;
}
return 0;
}
#endif
#if KWSYS_CXX_HAS_SETENV
/* setenv("A", "B", 1) will set A=B in the environment and makes its
own copies of the strings. */
bool SystemTools::PutEnv(const std::string& env)
{
size_t pos = env.find('=');
if (pos != std::string::npos) {
std::string name = env.substr(0, pos);
return setenv(name.c_str(), env.c_str() + pos + 1, 1) == 0;
} else {
return kwsysUnPutEnv(env) == 0;
}
}
bool SystemTools::UnPutEnv(const std::string& env)
{
return kwsysUnPutEnv(env) == 0;
}
#else
/* putenv("A=B") will set A=B in the environment. Most putenv implementations
put their argument directly in the environment. They never free the memory
on program exit. Keep an active set of pointers to memory we allocate and
pass to putenv, one per environment key. At program exit remove any
environment values that may still reference memory we allocated. Then free
the memory. This will not affect any environment values we never set. */
# ifdef __INTEL_COMPILER
# pragma warning disable 444 /* base has non-virtual destructor */
# endif
class kwsysEnv : public kwsysEnvSet
{
public:
~kwsysEnv()
{
for (iterator i = this->begin(); i != this->end(); ++i) {
# if defined(_WIN32)
const std::string s = Encoding::ToNarrow(*i);
kwsysUnPutEnv(s);
# else
kwsysUnPutEnv(*i);
# endif
free(const_cast<envchar*>(*i));
}
}
bool Put(const char* env)
{
# if defined(_WIN32)
const std::wstring wEnv = Encoding::ToWide(env);
wchar_t* newEnv = _wcsdup(wEnv.c_str());
# else
char* newEnv = strdup(env);
# endif
Free oldEnv(this->Release(newEnv));
this->insert(newEnv);
# if defined(_WIN32)
return _wputenv(newEnv) == 0;
# else
return putenv(newEnv) == 0;
# endif
}
bool UnPut(const char* env)
{
# if defined(_WIN32)
const std::wstring wEnv = Encoding::ToWide(env);
Free oldEnv(this->Release(wEnv.c_str()));
# else
Free oldEnv(this->Release(env));
# endif
return kwsysUnPutEnv(env) == 0;
}
};
static kwsysEnv kwsysEnvInstance;
bool SystemTools::PutEnv(const std::string& env)
{
return kwsysEnvInstance.Put(env.c_str());
}
bool SystemTools::UnPutEnv(const std::string& env)
{
return kwsysEnvInstance.UnPut(env.c_str());
}
#endif
const char* SystemTools::GetExecutableExtension()
{
#if defined(_WIN32) || defined(__CYGWIN__) || defined(__VMS)
return ".exe";
#else
return "";
#endif
}
FILE* SystemTools::Fopen(const std::string& file, const char* mode)
{
#ifdef _WIN32