-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathoperations.cpp
2452 lines (2131 loc) · 78.2 KB
/
operations.cpp
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
// operations.cpp --------------------------------------------------------------------//
// Copyright 2002-2009, 2014 Beman Dawes
// Copyright 2001 Dietmar Kuehl
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// See library home page at http://www.boost.org/libs/filesystem
//--------------------------------------------------------------------------------------//
// define 64-bit offset macros BEFORE including boost/config.hpp (see ticket #5355)
#if !(defined(__HP_aCC) && defined(_ILP32) && !defined(_STATVFS_ACPP_PROBLEMS_FIXED))
#define _FILE_OFFSET_BITS 64 // at worst, these defines may have no effect,
#endif
#if !defined(__PGI)
#define __USE_FILE_OFFSET64 // but that is harmless on Windows and on POSIX
// 64-bit systems or on 32-bit systems which don't have files larger
// than can be represented by a traditional POSIX/UNIX off_t type.
// OTOH, defining them should kick in 64-bit off_t's (and thus
// st_size)on 32-bit systems that provide the Large File
// Support (LFS)interface, such as Linux, Solaris, and IRIX.
// The defines are given before any headers are included to
// ensure that they are available to all included headers.
// That is required at least on Solaris, and possibly on other
// systems as well.
#else
#define _FILE_OFFSET_BITS 64
#endif
// define BOOST_FILESYSTEM_SOURCE so that <boost/filesystem/config.hpp> knows
// the library is being built (possibly exporting rather than importing code)
#define BOOST_FILESYSTEM_SOURCE
#ifndef BOOST_SYSTEM_NO_DEPRECATED
# define BOOST_SYSTEM_NO_DEPRECATED
#endif
#ifndef _POSIX_PTHREAD_SEMANTICS
# define _POSIX_PTHREAD_SEMANTICS // Sun readdir_r()needs this
#endif
#include <boost/filesystem/operations.hpp>
#include <boost/scoped_array.hpp>
#include <boost/detail/workaround.hpp>
#include <vector>
#include <cstdlib> // for malloc, free
#include <cstring>
#include <cstdio> // for remove, rename
#if defined(__QNXNTO__) // see ticket #5355
# include <stdio.h>
#endif
#include <cerrno>
#ifdef BOOST_FILEYSTEM_INCLUDE_IOSTREAM
# include <iostream>
#endif
namespace fs = boost::filesystem;
using boost::filesystem::path;
using boost::filesystem::filesystem_error;
using boost::filesystem::perms;
using boost::system::error_code;
using boost::system::error_category;
using boost::system::system_category;
using std::string;
using std::wstring;
# ifdef BOOST_POSIX_API
# include <sys/types.h>
# include <sys/stat.h>
# if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__ANDROID__) \
&& !defined(__VXWORKS__)
# include <sys/statvfs.h>
# define BOOST_STATVFS statvfs
# define BOOST_STATVFS_F_FRSIZE vfs.f_frsize
# else
# ifdef __OpenBSD__
# include <sys/param.h>
# elif defined(__ANDROID__)
# include <sys/vfs.h>
# endif
# if !defined(__VXWORKS__)
# include <sys/mount.h>
# endif
# define BOOST_STATVFS statfs
# define BOOST_STATVFS_F_FRSIZE static_cast<boost::uintmax_t>(vfs.f_bsize)
# endif
# include <dirent.h>
# include <unistd.h>
# include <fcntl.h>
# include <utime.h>
# include "limits.h"
# else // BOOST_WINDOW_API
# if (defined(__MINGW32__) || defined(__CYGWIN__)) && !defined(WINVER)
// Versions of MinGW or Cygwin that support Filesystem V3 support at least WINVER 0x501.
// See MinGW's windef.h
# define WINVER 0x501
# endif
# include <cwchar>
# include <io.h>
# include <windows.h>
# include <winnt.h>
# if !defined(_WIN32_WINNT)
# define _WIN32_WINNT 0x0500
# endif
# if defined(__BORLANDC__) || defined(__MWERKS__)
# if defined(__BORLANDC__)
using std::time_t;
# endif
# include <utime.h>
# else
# include <sys/utime.h>
# endif
// REPARSE_DATA_BUFFER related definitions are found in ntifs.h, which is part of the
// Windows Device Driver Kit. Since that's inconvenient, the definitions are provided
// here. See http://msdn.microsoft.com/en-us/library/ms791514.aspx
#if !defined(REPARSE_DATA_BUFFER_HEADER_SIZE) // mingw winnt.h does provide the defs
#define SYMLINK_FLAG_RELATIVE 1
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];
/* Example of distinction between substitute and print names:
mklink /d ldrive c:\
SubstituteName: c:\\??\
PrintName: c:\
*/
} SymbolicLinkReparseBuffer;
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
WCHAR PathBuffer[1];
} MountPointReparseBuffer;
struct {
UCHAR DataBuffer[1];
} GenericReparseBuffer;
};
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
#define REPARSE_DATA_BUFFER_HEADER_SIZE \
FIELD_OFFSET(REPARSE_DATA_BUFFER, GenericReparseBuffer)
#endif
#ifndef MAXIMUM_REPARSE_DATA_BUFFER_SIZE
#define MAXIMUM_REPARSE_DATA_BUFFER_SIZE ( 16 * 1024 )
#endif
# ifndef FSCTL_GET_REPARSE_POINT
# define FSCTL_GET_REPARSE_POINT 0x900a8
# endif
# ifndef IO_REPARSE_TAG_SYMLINK
# define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
# endif
inline std::wstring wgetenv(const wchar_t* name)
{
// use vector since for C++03 basic_string is not required to be contiguous
std::vector<wchar_t> buf(::GetEnvironmentVariableW(name, NULL, 0));
// C++03 vector does not have data() so use &buf[0]
return (buf.empty()
|| ::GetEnvironmentVariableW(name, &buf[0], static_cast<DWORD>(buf.size())) == 0)
? std::wstring() : std::wstring(&buf[0]);
}
# endif // BOOST_WINDOWS_API
// BOOST_FILESYSTEM_STATUS_CACHE enables file_status cache in
// dir_itr_increment. The config tests are placed here because some of the
// macros being tested come from dirent.h.
//
// TODO: find out what macros indicate dirent::d_type present in more libraries
# if defined(BOOST_WINDOWS_API)\
|| defined(_DIRENT_HAVE_D_TYPE)// defined by GNU C library if d_type present
# define BOOST_FILESYSTEM_STATUS_CACHE
# endif
// POSIX/Windows macros ----------------------------------------------------//
// Portions of the POSIX and Windows API's are very similar, except for name,
// order of arguments, and meaning of zero/non-zero returns. The macros below
// abstract away those differences. They follow Windows naming and order of
// arguments, and return true to indicate no error occurred. [POSIX naming,
// order of arguments, and meaning of return were followed initially, but
// found to be less clear and cause more coding errors.]
# if defined(BOOST_POSIX_API)
typedef int err_t;
// POSIX uses a 0 return to indicate success
# define BOOST_ERRNO errno
# define BOOST_SET_CURRENT_DIRECTORY(P)(::chdir(P)== 0)
# define BOOST_CREATE_DIRECTORY(P)(::mkdir(P, S_IRWXU|S_IRWXG|S_IRWXO)== 0)
# define BOOST_CREATE_HARD_LINK(F,T)(::link(T, F)== 0)
# define BOOST_CREATE_SYMBOLIC_LINK(F,T,Flag)(::symlink(T, F)== 0)
# define BOOST_REMOVE_DIRECTORY(P)(::rmdir(P)== 0)
# define BOOST_DELETE_FILE(P)(::unlink(P)== 0)
# define BOOST_COPY_DIRECTORY(F,T)(!(::stat(from.c_str(), &from_stat)!= 0\
|| ::mkdir(to.c_str(),from_stat.st_mode)!= 0))
# define BOOST_COPY_FILE(F,T,FailIfExistsBool)copy_file_api(F, T, FailIfExistsBool)
# define BOOST_MOVE_FILE(OLD,NEW)(::rename(OLD, NEW)== 0)
# define BOOST_RESIZE_FILE(P,SZ)(::truncate(P, SZ)== 0)
# define BOOST_ERROR_NOT_SUPPORTED ENOSYS
# define BOOST_ERROR_ALREADY_EXISTS EEXIST
# else // BOOST_WINDOWS_API
typedef DWORD err_t;
// Windows uses a non-0 return to indicate success
# define BOOST_ERRNO ::GetLastError()
# define BOOST_SET_CURRENT_DIRECTORY(P)(::SetCurrentDirectoryW(P)!= 0)
# define BOOST_CREATE_DIRECTORY(P)(::CreateDirectoryW(P, 0)!= 0)
# define BOOST_CREATE_HARD_LINK(F,T)(create_hard_link_api(F, T, 0)!= 0)
# define BOOST_CREATE_SYMBOLIC_LINK(F,T,Flag)(create_symbolic_link_api(F, T, Flag)!= 0)
# define BOOST_REMOVE_DIRECTORY(P)(::RemoveDirectoryW(P)!= 0)
# define BOOST_DELETE_FILE(P)(::DeleteFileW(P)!= 0)
# define BOOST_COPY_DIRECTORY(F,T)(::CreateDirectoryExW(F, T, 0)!= 0)
# define BOOST_COPY_FILE(F,T,FailIfExistsBool)(::CopyFileW(F, T, FailIfExistsBool)!= 0)
# define BOOST_MOVE_FILE(OLD,NEW)(::MoveFileExW(OLD, NEW, MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED)!= 0)
# define BOOST_RESIZE_FILE(P,SZ)(resize_file_api(P, SZ)!= 0)
# define BOOST_READ_SYMLINK(P,T)
# define BOOST_ERROR_ALREADY_EXISTS ERROR_ALREADY_EXISTS
# define BOOST_ERROR_NOT_SUPPORTED ERROR_NOT_SUPPORTED
# endif
//--------------------------------------------------------------------------------------//
// //
// helpers (all operating systems) //
// //
//--------------------------------------------------------------------------------------//
namespace
{
fs::file_type query_file_type(const path& p, error_code* ec);
boost::filesystem::directory_iterator end_dir_itr;
// error handling helpers ----------------------------------------------------------//
bool error(err_t error_num, error_code* ec, const char* message);
bool error(err_t error_num, const path& p, error_code* ec, const char* message);
bool error(err_t error_num, const path& p1, const path& p2, error_code* ec,
const char* message);
const error_code ok;
// error_num is value of errno on POSIX, error code (from ::GetLastError()) on Windows.
// Interface changed 30 Jan 15 to have caller supply error_num as ::SetLastError()
// values were apparently getting cleared before they could be retrieved by error().
bool error(err_t error_num, error_code* ec, const char* message)
{
if (!error_num)
{
if (ec != 0) ec->clear();
}
else
{ // error
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(message,
error_code(error_num, system_category())));
else
ec->assign(error_num, system_category());
}
return error_num != 0;
}
bool error(err_t error_num, const path& p, error_code* ec, const char* message)
{
if (!error_num)
{
if (ec != 0) ec->clear();
}
else
{ // error
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(message,
p, error_code(error_num, system_category())));
else
ec->assign(error_num, system_category());
}
return error_num != 0;
}
bool error(err_t error_num, const path& p1, const path& p2, error_code* ec,
const char* message)
{
if (!error_num)
{
if (ec != 0) ec->clear();
}
else
{ // error
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(message,
p1, p2, error_code(error_num, system_category())));
else
ec->assign(error_num, system_category());
}
return error_num != 0;
}
// general helpers -----------------------------------------------------------------//
bool is_empty_directory(const path& p, error_code* ec)
{
return (ec != 0 ? fs::directory_iterator(p, *ec) : fs::directory_iterator(p))
== end_dir_itr;
}
bool not_found_error(int errval); // forward declaration
// only called if directory exists
bool remove_directory(const path& p) // true if succeeds or not found
{
return BOOST_REMOVE_DIRECTORY(p.c_str())
|| not_found_error(BOOST_ERRNO); // mitigate possible file system race. See #11166
}
// only called if file exists
bool remove_file(const path& p) // true if succeeds or not found
{
return BOOST_DELETE_FILE(p.c_str())
|| not_found_error(BOOST_ERRNO); // mitigate possible file system race. See #11166
}
// called by remove and remove_all_aux
bool remove_file_or_directory(const path& p, fs::file_type type, error_code* ec)
// return true if file removed, false if not removed
{
if (type == fs::file_not_found)
{
if (ec != 0) ec->clear();
return false;
}
if (type == fs::directory_file
# ifdef BOOST_WINDOWS_API
|| type == fs::_detail_directory_symlink
# endif
)
{
if (error(!remove_directory(p) ? BOOST_ERRNO : 0, p, ec,
"boost::filesystem::remove"))
return false;
}
else
{
if (error(!remove_file(p) ? BOOST_ERRNO : 0, p, ec,
"boost::filesystem::remove"))
return false;
}
return true;
}
boost::uintmax_t remove_all_aux(const path& p, fs::file_type type,
error_code* ec)
{
boost::uintmax_t count = 1;
if (type == fs::directory_file) // but not a directory symlink
{
fs::directory_iterator itr;
if (ec != 0)
{
itr = fs::directory_iterator(p, *ec);
if (*ec)
return count;
}
else
itr = fs::directory_iterator(p);
for (; itr != end_dir_itr; ++itr)
{
fs::file_type tmp_type = query_file_type(itr->path(), ec);
if (ec != 0 && *ec)
return count;
count += remove_all_aux(itr->path(), tmp_type, ec);
if (ec != 0 && *ec)
return count;
}
}
remove_file_or_directory(p, type, ec);
return count;
}
#ifdef BOOST_POSIX_API
//--------------------------------------------------------------------------------------//
// //
// POSIX-specific helpers //
// //
//--------------------------------------------------------------------------------------//
const char dot = '.';
bool not_found_error(int errval)
{
return errno == ENOENT || errno == ENOTDIR;
}
bool // true if ok
copy_file_api(const std::string& from_p,
const std::string& to_p, bool fail_if_exists)
{
const std::size_t buf_sz = 32768;
boost::scoped_array<char> buf(new char [buf_sz]);
int infile=-1, outfile=-1; // -1 means not open
// bug fixed: code previously did a stat()on the from_file first, but that
// introduced a gratuitous race condition; the stat()is now done after the open()
if ((infile = ::open(from_p.c_str(), O_RDONLY))< 0)
{ return false; }
struct stat from_stat;
if (::stat(from_p.c_str(), &from_stat)!= 0)
{
::close(infile);
return false;
}
int oflag = O_CREAT | O_WRONLY | O_TRUNC;
if (fail_if_exists)
oflag |= O_EXCL;
if ((outfile = ::open(to_p.c_str(), oflag, from_stat.st_mode))< 0)
{
int open_errno = errno;
BOOST_ASSERT(infile >= 0);
::close(infile);
errno = open_errno;
return false;
}
ssize_t sz, sz_read=1, sz_write;
while (sz_read > 0
&& (sz_read = ::read(infile, buf.get(), buf_sz)) > 0)
{
// Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
// Marc Rochkind, Addison-Wesley, 2004, page 94
sz_write = 0;
do
{
BOOST_ASSERT(sz_read - sz_write > 0); // #1
// ticket 4438 claimed possible infinite loop if write returns 0. My analysis
// is that POSIX specifies 0 return only if 3rd arg is 0, and that will never
// happen due to loop entry and coninuation conditions. BOOST_ASSERT #1 above
// and #2 below added to verify that analysis.
if ((sz = ::write(outfile, buf.get() + sz_write,
sz_read - sz_write)) < 0)
{
sz_read = sz; // cause read loop termination
break; // and error reported after closes
}
BOOST_ASSERT(sz > 0); // #2
sz_write += sz;
} while (sz_write < sz_read);
}
if (::close(infile)< 0)
sz_read = -1;
if (::close(outfile)< 0)
sz_read = -1;
return sz_read >= 0;
}
inline fs::file_type query_file_type(const path& p, error_code* ec)
{
return fs::detail::symlink_status(p, ec).type();
}
# else
//--------------------------------------------------------------------------------------//
// //
// Windows-specific helpers //
// //
//--------------------------------------------------------------------------------------//
const std::size_t buf_size=128;
const wchar_t dot = L'.';
bool not_found_error(int errval)
{
return errval == ERROR_FILE_NOT_FOUND
|| errval == ERROR_PATH_NOT_FOUND
|| errval == ERROR_INVALID_NAME // "tools/jam/src/:sys:stat.h", "//foo"
|| errval == ERROR_INVALID_DRIVE // USB card reader with no card inserted
|| errval == ERROR_NOT_READY // CD/DVD drive with no disc inserted
|| errval == ERROR_INVALID_PARAMETER // ":sys:stat.h"
|| errval == ERROR_BAD_PATHNAME // "//nosuch" on Win64
|| errval == ERROR_BAD_NETPATH; // "//nosuch" on Win32
}
// File name case-insensitive comparison needs to be locale- and collation-independent.
// The approach used below follows a combined strategy described in the following
// articles:
// http://archives.miloush.net/michkap/archive/2005/10/17/481600.html
// http://archives.miloush.net/michkap/archive/2007/09/14/4900107.html
// http://archives.miloush.net/michkap/archive/2007/10/12/5396685.html
// CompareStringOrdinal is only available on newer systems and is just a wrapper of
// RtlCompareUnicodeString, but measurements showed that RtlEqualUnicodeString has better
// performance. Therefore we use RtlEqualUnicodeString, and if that does not exist
// we perform the equivalent characterwise comparsion using LCMapString and uppercase
// binary equality. Instead of calling RtlInitUnicodeString we use wcslen directly
// because that results in better performance as well.
// Windows ntdll.dll functions that may or may not be present
// must be accessed through pointers
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING;
typedef const UNICODE_STRING *PCUNICODE_STRING;
typedef BOOLEAN (WINAPI *PtrRtlEqualUnicodeString)(
/*_In_*/ PCUNICODE_STRING String1,
/*_In_*/ PCUNICODE_STRING String2,
/*_In_*/ BOOLEAN CaseInSensitive
);
PtrRtlEqualUnicodeString rtl_equal_unicode_string_api = PtrRtlEqualUnicodeString(
::GetProcAddress(
::GetModuleHandleW(L"ntdll.dll"), "RtlEqualUnicodeString"));
#ifndef LOCALE_INVARIANT
# define LOCALE_INVARIANT (MAKELCID(MAKELANGID(LANG_INVARIANT, SUBLANG_NEUTRAL), SORT_DEFAULT))
#endif
bool equal_string_ordinal_ic_1(const wchar_t* s1, const wchar_t* s2)
{
std::size_t len1 = std::wcslen(s1);
UNICODE_STRING us1;
us1.Buffer = const_cast<wchar_t*>(s1);
us1.Length = static_cast<USHORT>(sizeof(*s1) * len1);
us1.MaximumLength = static_cast<USHORT>(us1.Length + sizeof(*s1));
std::size_t len2 = std::wcslen(s2);
UNICODE_STRING us2;
us2.Buffer = const_cast<wchar_t*>(s2);
us2.Length = static_cast<USHORT>(sizeof(*s2) * len2);
us2.MaximumLength = static_cast<USHORT>(us2.Length + sizeof(*s2));
BOOLEAN res = rtl_equal_unicode_string_api(&us1, &us2, TRUE);
return res != FALSE;
}
inline
wchar_t to_upper_invariant(wchar_t input)
{
wchar_t result;
// According to
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd318144(v=vs.85).aspx
// "When transforming between uppercase and lowercase, the function always maps a
// single character to a single character."
int res = ::LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, &input, 1, &result, 1);
if (res != 0)
return result;
assert(!"LCMapStringW failed to convert a character to upper case");
return input; // Should never happen, but this is a safe fallback.
}
bool equal_string_ordinal_ic_2(const wchar_t* s1, const wchar_t* s2)
{
for (;; ++s1, ++s2)
{
const wchar_t c1 = *s1;
const wchar_t c2 = *s2;
if (c1 == c2)
{
if (!c1)
return true; // We have reached the end of both strings, no difference found.
}
else
{
if (!c1 || !c2)
return false; // We have reached the end of one string
// This needs to be upper case to match the behavior of the operating system,
// see http://archives.miloush.net/michkap/archive/2005/10/17/481600.html
const wchar_t u1 = to_upper_invariant(c1);
const wchar_t u2 = to_upper_invariant(c2);
if (u1 != u2)
return false; // strings are different
}
}
}
typedef bool (*Ptr_equal_string_ordinal_ic)(const wchar_t*, const wchar_t*);
Ptr_equal_string_ordinal_ic equal_string_ordinal_ic =
rtl_equal_unicode_string_api ? equal_string_ordinal_ic_1 : equal_string_ordinal_ic_2;
perms make_permissions(const path& p, DWORD attr)
{
perms prms = fs::owner_read | fs::group_read | fs::others_read;
if ((attr & FILE_ATTRIBUTE_READONLY) == 0)
prms |= fs::owner_write | fs::group_write | fs::others_write;
path ext = p.extension();
if (equal_string_ordinal_ic(ext.c_str(), L".exe")
|| equal_string_ordinal_ic(ext.c_str(), L".com")
|| equal_string_ordinal_ic(ext.c_str(), L".bat")
|| equal_string_ordinal_ic(ext.c_str(), L".cmd"))
prms |= fs::owner_exe | fs::group_exe | fs::others_exe;
return prms;
}
// these constants come from inspecting some Microsoft sample code
std::time_t to_time_t(const FILETIME & ft)
{
__int64 t = (static_cast<__int64>(ft.dwHighDateTime)<< 32)
+ ft.dwLowDateTime;
# if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 // > VC++ 7.0
t -= 116444736000000000LL;
# else
t -= 116444736000000000;
# endif
t /= 10000000;
return static_cast<std::time_t>(t);
}
void to_FILETIME(std::time_t t, FILETIME & ft)
{
__int64 temp = t;
temp *= 10000000;
# if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 // > VC++ 7.0
temp += 116444736000000000LL;
# else
temp += 116444736000000000;
# endif
ft.dwLowDateTime = static_cast<DWORD>(temp);
ft.dwHighDateTime = static_cast<DWORD>(temp >> 32);
}
// Thanks to Jeremy Maitin-Shepard for much help and for permission to
// base the equivalent()implementation on portions of his
// file-equivalence-win32.cpp experimental code.
struct handle_wrapper
{
HANDLE handle;
handle_wrapper(HANDLE h)
: handle(h){}
~handle_wrapper()
{
if (handle != INVALID_HANDLE_VALUE)
::CloseHandle(handle);
}
};
HANDLE create_file_handle(const path& p, DWORD dwDesiredAccess,
DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile)
{
return ::CreateFileW(p.c_str(), dwDesiredAccess, dwShareMode,
lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes,
hTemplateFile);
}
bool is_reparse_point_a_symlink(const path& p)
{
handle_wrapper h(create_file_handle(p, FILE_READ_EA,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL));
if (h.handle == INVALID_HANDLE_VALUE)
return false;
boost::scoped_array<char> buf(new char [MAXIMUM_REPARSE_DATA_BUFFER_SIZE]);
// Query the reparse data
DWORD dwRetLen;
BOOL result = ::DeviceIoControl(h.handle, FSCTL_GET_REPARSE_POINT, NULL, 0, buf.get(),
MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &dwRetLen, NULL);
if (!result) return false;
return reinterpret_cast<const REPARSE_DATA_BUFFER*>(buf.get())->ReparseTag
== IO_REPARSE_TAG_SYMLINK
// Issue 9016 asked that NTFS directory junctions be recognized as directories.
// That is equivalent to recognizing them as symlinks, and then the normal symlink
// mechanism will take care of recognizing them as directories.
//
// Directory junctions are very similar to symlinks, but have some performance
// and other advantages over symlinks. They can be created from the command line
// with "mklink /j junction-name target-path".
|| reinterpret_cast<const REPARSE_DATA_BUFFER*>(buf.get())->ReparseTag
== IO_REPARSE_TAG_MOUNT_POINT; // aka "directory junction" or "junction"
}
inline std::size_t get_full_path_name(
const path& src, std::size_t len, wchar_t* buf, wchar_t** p)
{
return static_cast<std::size_t>(
::GetFullPathNameW(src.c_str(), static_cast<DWORD>(len), buf, p));
}
fs::file_status process_status_failure(const path& p, error_code* ec)
{
int errval(::GetLastError());
if (ec != 0) // always report errval, even though some
ec->assign(errval, system_category()); // errval values are not status_errors
if (not_found_error(errval))
{
return fs::file_status(fs::file_not_found, fs::no_perms);
}
else if ((errval == ERROR_SHARING_VIOLATION))
{
return fs::file_status(fs::type_unknown);
}
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error("boost::filesystem::status",
p, error_code(errval, system_category())));
return fs::file_status(fs::status_error);
}
// differs from symlink_status() in that directory symlinks are reported as
// _detail_directory_symlink, as required on Windows by remove() and its helpers.
fs::file_type query_file_type(const path& p, error_code* ec)
{
DWORD attr(::GetFileAttributesW(p.c_str()));
if (attr == 0xFFFFFFFF)
{
return process_status_failure(p, ec).type();
}
if (ec != 0) ec->clear();
if (attr & FILE_ATTRIBUTE_REPARSE_POINT)
{
if (is_reparse_point_a_symlink(p))
return (attr & FILE_ATTRIBUTE_DIRECTORY)
? fs::_detail_directory_symlink
: fs::symlink_file;
return fs::reparse_file;
}
return (attr & FILE_ATTRIBUTE_DIRECTORY)
? fs::directory_file
: fs::regular_file;
}
BOOL resize_file_api(const wchar_t* p, boost::uintmax_t size)
{
handle_wrapper h(CreateFileW(p, GENERIC_WRITE, 0, 0, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0));
LARGE_INTEGER sz;
sz.QuadPart = size;
return h.handle != INVALID_HANDLE_VALUE
&& ::SetFilePointerEx(h.handle, sz, 0, FILE_BEGIN)
&& ::SetEndOfFile(h.handle);
}
// Windows kernel32.dll functions that may or may not be present
// must be accessed through pointers
typedef BOOL (WINAPI *PtrCreateHardLinkW)(
/*__in*/ LPCWSTR lpFileName,
/*__in*/ LPCWSTR lpExistingFileName,
/*__reserved*/ LPSECURITY_ATTRIBUTES lpSecurityAttributes
);
PtrCreateHardLinkW create_hard_link_api = PtrCreateHardLinkW(
::GetProcAddress(
::GetModuleHandleW(L"kernel32.dll"), "CreateHardLinkW"));
typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
/*__in*/ LPCWSTR lpSymlinkFileName,
/*__in*/ LPCWSTR lpTargetFileName,
/*__in*/ DWORD dwFlags
);
PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
::GetProcAddress(
::GetModuleHandleW(L"kernel32.dll"), "CreateSymbolicLinkW"));
#endif
//#ifdef BOOST_WINDOWS_API
//
//
// inline bool get_free_disk_space(const std::wstring& ph,
// PULARGE_INTEGER avail, PULARGE_INTEGER total, PULARGE_INTEGER free)
// { return ::GetDiskFreeSpaceExW(ph.c_str(), avail, total, free)!= 0; }
//
//#endif
} // unnamed namespace
//--------------------------------------------------------------------------------------//
// //
// operations functions declared in operations.hpp //
// in alphabetic order //
// //
//--------------------------------------------------------------------------------------//
namespace boost
{
namespace filesystem
{
BOOST_FILESYSTEM_DECL
path absolute(const path& p, const path& base)
{
// if ( p.empty() || p.is_absolute() )
// return p;
// // recursively calling absolute is sub-optimal, but is simple
// path abs_base(base.is_absolute() ? base : absolute(base));
//# ifdef BOOST_WINDOWS_API
// if (p.has_root_directory())
// return abs_base.root_name() / p;
// // !p.has_root_directory
// if (p.has_root_name())
// return p.root_name()
// / abs_base.root_directory() / abs_base.relative_path() / p.relative_path();
// // !p.has_root_name()
//# endif
// return abs_base / p;
// recursively calling absolute is sub-optimal, but is sure and simple
path abs_base(base.is_absolute() ? base : absolute(base));
// store expensive to compute values that are needed multiple times
path p_root_name (p.root_name());
path base_root_name (abs_base.root_name());
path p_root_directory (p.root_directory());
if (p.empty())
return abs_base;
if (!p_root_name.empty()) // p.has_root_name()
{
if (p_root_directory.empty()) // !p.has_root_directory()
return p_root_name / abs_base.root_directory()
/ abs_base.relative_path() / p.relative_path();
// p is absolute, so fall through to return p at end of block
}
else if (!p_root_directory.empty()) // p.has_root_directory()
{
# ifdef BOOST_POSIX_API
// POSIX can have root name it it is a network path
if (base_root_name.empty()) // !abs_base.has_root_name()
return p;
# endif
return base_root_name / p;
}
else
{
return abs_base / p;
}
return p; // p.is_absolute() is true
}
namespace detail
{
BOOST_FILESYSTEM_DECL bool possible_large_file_size_support()
{
# ifdef BOOST_POSIX_API
struct stat lcl_stat;
return sizeof(lcl_stat.st_size)> 4;
# else
return true;
# endif
}
BOOST_FILESYSTEM_DECL
path canonical(const path& p, const path& base, system::error_code* ec)
{
path source (p.is_absolute() ? p : absolute(p, base));
path root(source.root_path());
path result;
system::error_code local_ec;
file_status stat (status(source, local_ec));
if (stat.type() == fs::file_not_found)
{
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(
"boost::filesystem::canonical", source,
error_code(system::errc::no_such_file_or_directory, system::generic_category())));
ec->assign(system::errc::no_such_file_or_directory, system::generic_category());
return result;
}
else if (local_ec)
{
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(
"boost::filesystem::canonical", source, local_ec));
*ec = local_ec;
return result;
}
bool scan (true);
while (scan)
{
scan = false;
result.clear();
for (path::iterator itr = source.begin(); itr != source.end(); ++itr)
{
if (*itr == dot_path())
continue;
if (*itr == dot_dot_path())
{
if (result != root)
result.remove_filename();
continue;
}
result /= *itr;
bool is_sym (is_symlink(detail::symlink_status(result, ec)));
if (ec && *ec)
return path();
if (is_sym)
{
path link(detail::read_symlink(result, ec));
if (ec && *ec)
return path();
result.remove_filename();
if (link.is_absolute())
{
for (++itr; itr != source.end(); ++itr)
link /= *itr;
source = link;
}
else // link is relative
{
path new_source(result);
new_source /= link;
for (++itr; itr != source.end(); ++itr)
new_source /= *itr;
source = new_source;
}
scan = true; // symlink causes scan to be restarted
break;
}
}
}
if (ec != 0)
ec->clear();
BOOST_ASSERT_MSG(result.is_absolute(), "canonical() implementation error; please report");
return result;
}
BOOST_FILESYSTEM_DECL
void copy(const path& from, const path& to, system::error_code* ec)
{
file_status s(symlink_status(from, *ec));
if (ec != 0 && *ec) return;
if(is_symlink(s))
{
copy_symlink(from, to, *ec);
}
else if(is_directory(s))
{
copy_directory(from, to, *ec);
}
else if(is_regular_file(s))
{
copy_file(from, to, fs::copy_option::fail_if_exists, *ec);
}
else
{
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error("boost::filesystem::copy",
from, to, error_code(BOOST_ERROR_NOT_SUPPORTED, system_category())));
ec->assign(BOOST_ERROR_NOT_SUPPORTED, system_category());