forked from rust-lang/rust
/
file.rs
977 lines (880 loc) · 31.8 KB
/
file.rs
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
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Blocking posix-based file I/O
use std::c_str::CString;
use std::io::IoError;
use std::io;
use std::libc::{c_int, c_void};
use std::libc;
use std::os;
use std::rt::rtio;
use std::unstable::intrinsics;
use std::vec;
use io::{IoResult, retry};
#[cfg(windows)] use std::os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
#[cfg(windows)] use std::ptr;
#[cfg(windows)] use std::str;
pub fn keep_going(data: &[u8], f: |*u8, uint| -> i64) -> i64 {
#[cfg(windows)] static eintr: int = 0; // doesn't matter
#[cfg(not(windows))] static eintr: int = libc::EINTR as int;
let origamt = data.len();
let mut data = data.as_ptr();
let mut amt = origamt;
while amt > 0 {
let mut ret;
loop {
ret = f(data, amt);
if cfg!(windows) { break } // windows has no eintr
// if we get an eintr, then try again
if ret != -1 || os::errno() as int != eintr { break }
}
if ret == 0 {
break
} else if ret != -1 {
amt -= ret as uint;
data = unsafe { data.offset(ret as int) };
} else {
return ret;
}
}
return (origamt - amt) as i64;
}
pub type fd_t = libc::c_int;
pub struct FileDesc {
priv fd: fd_t,
priv close_on_drop: bool,
}
impl FileDesc {
/// Create a `FileDesc` from an open C file descriptor.
///
/// The `FileDesc` will take ownership of the specified file descriptor and
/// close it upon destruction if the `close_on_drop` flag is true, otherwise
/// it will not close the file descriptor when this `FileDesc` is dropped.
///
/// Note that all I/O operations done on this object will be *blocking*, but
/// they do not require the runtime to be active.
pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
FileDesc { fd: fd, close_on_drop: close_on_drop }
}
// FIXME(#10465) these functions should not be public, but anything in
// native::io wanting to use them is forced to have all the
// rtio traits in scope
pub fn inner_read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
#[cfg(windows)] type rlen = libc::c_uint;
#[cfg(not(windows))] type rlen = libc::size_t;
let ret = retry(|| unsafe {
libc::read(self.fd,
buf.as_ptr() as *mut libc::c_void,
buf.len() as rlen) as libc::c_int
});
if ret == 0 {
Err(io::standard_error(io::EndOfFile))
} else if ret < 0 {
Err(super::last_error())
} else {
Ok(ret as uint)
}
}
pub fn inner_write(&mut self, buf: &[u8]) -> Result<(), IoError> {
#[cfg(windows)] type wlen = libc::c_uint;
#[cfg(not(windows))] type wlen = libc::size_t;
let ret = keep_going(buf, |buf, len| {
unsafe {
libc::write(self.fd, buf as *libc::c_void, len as wlen) as i64
}
});
if ret < 0 {
Err(super::last_error())
} else {
Ok(())
}
}
pub fn fd(&self) -> fd_t { self.fd }
}
impl io::Reader for FileDesc {
fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
match self.inner_read(buf) { Ok(n) => Some(n), Err(..) => None }
}
}
impl io::Writer for FileDesc {
fn write(&mut self, buf: &[u8]) {
match self.inner_write(buf) {
Ok(()) => {}
Err(e) => { io::io_error::cond.raise(e); }
}
}
}
impl rtio::RtioFileStream for FileDesc {
fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError> {
self.inner_read(buf).map(|i| i as int)
}
fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
self.inner_write(buf)
}
fn pread(&mut self, buf: &mut [u8], offset: u64) -> Result<int, IoError> {
return os_pread(self.fd, buf.as_ptr(), buf.len(), offset);
#[cfg(windows)]
fn os_pread(fd: c_int, buf: *u8, amt: uint, offset: u64) -> IoResult<int> {
unsafe {
let mut overlap: libc::OVERLAPPED = intrinsics::init();
let handle = libc::get_osfhandle(fd) as libc::HANDLE;
let mut bytes_read = 0;
overlap.Offset = offset as libc::DWORD;
overlap.OffsetHigh = (offset >> 32) as libc::DWORD;
match libc::ReadFile(handle, buf as libc::LPVOID,
amt as libc::DWORD,
&mut bytes_read, &mut overlap) {
0 => Err(super::last_error()),
_ => Ok(bytes_read as int)
}
}
}
#[cfg(unix)]
fn os_pread(fd: c_int, buf: *u8, amt: uint, offset: u64) -> IoResult<int> {
match retry(|| unsafe {
libc::pread(fd, buf as *libc::c_void, amt as libc::size_t,
offset as libc::off_t) as libc::c_int
}) {
-1 => Err(super::last_error()),
n => Ok(n as int)
}
}
}
fn pwrite(&mut self, buf: &[u8], offset: u64) -> Result<(), IoError> {
return os_pwrite(self.fd, buf.as_ptr(), buf.len(), offset);
#[cfg(windows)]
fn os_pwrite(fd: c_int, buf: *u8, amt: uint, offset: u64) -> IoResult<()> {
unsafe {
let mut overlap: libc::OVERLAPPED = intrinsics::init();
let handle = libc::get_osfhandle(fd) as libc::HANDLE;
overlap.Offset = offset as libc::DWORD;
overlap.OffsetHigh = (offset >> 32) as libc::DWORD;
match libc::WriteFile(handle, buf as libc::LPVOID,
amt as libc::DWORD,
ptr::mut_null(), &mut overlap) {
0 => Err(super::last_error()),
_ => Ok(()),
}
}
}
#[cfg(unix)]
fn os_pwrite(fd: c_int, buf: *u8, amt: uint, offset: u64) -> IoResult<()> {
super::mkerr_libc(retry(|| unsafe {
libc::pwrite(fd, buf as *libc::c_void, amt as libc::size_t,
offset as libc::off_t)
} as c_int))
}
}
#[cfg(windows)]
fn seek(&mut self, pos: i64, style: io::SeekStyle) -> Result<u64, IoError> {
let whence = match style {
io::SeekSet => libc::FILE_BEGIN,
io::SeekEnd => libc::FILE_END,
io::SeekCur => libc::FILE_CURRENT,
};
unsafe {
let handle = libc::get_osfhandle(self.fd) as libc::HANDLE;
let mut newpos = 0;
match libc::SetFilePointerEx(handle, pos, &mut newpos, whence) {
0 => Err(super::last_error()),
_ => Ok(newpos as u64),
}
}
}
#[cfg(unix)]
fn seek(&mut self, pos: i64, whence: io::SeekStyle) -> Result<u64, IoError> {
let whence = match whence {
io::SeekSet => libc::SEEK_SET,
io::SeekEnd => libc::SEEK_END,
io::SeekCur => libc::SEEK_CUR,
};
let n = unsafe { libc::lseek(self.fd, pos as libc::off_t, whence) };
if n < 0 {
Err(super::last_error())
} else {
Ok(n as u64)
}
}
fn tell(&self) -> Result<u64, IoError> {
let n = unsafe { libc::lseek(self.fd, 0, libc::SEEK_CUR) };
if n < 0 {
Err(super::last_error())
} else {
Ok(n as u64)
}
}
fn fsync(&mut self) -> Result<(), IoError> {
return os_fsync(self.fd);
#[cfg(windows)]
fn os_fsync(fd: c_int) -> IoResult<()> {
super::mkerr_winbool(unsafe {
let handle = libc::get_osfhandle(fd);
libc::FlushFileBuffers(handle as libc::HANDLE)
})
}
#[cfg(unix)]
fn os_fsync(fd: c_int) -> IoResult<()> {
super::mkerr_libc(retry(|| unsafe { libc::fsync(fd) }))
}
}
#[cfg(windows)]
fn datasync(&mut self) -> Result<(), IoError> { return self.fsync(); }
#[cfg(not(windows))]
fn datasync(&mut self) -> Result<(), IoError> {
return super::mkerr_libc(os_datasync(self.fd));
#[cfg(target_os = "macos")]
fn os_datasync(fd: c_int) -> c_int {
unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
}
#[cfg(target_os = "linux")]
fn os_datasync(fd: c_int) -> c_int {
retry(|| unsafe { libc::fdatasync(fd) })
}
#[cfg(not(target_os = "macos"), not(target_os = "linux"))]
fn os_datasync(fd: c_int) -> c_int {
retry(|| unsafe { libc::fsync(fd) })
}
}
#[cfg(windows)]
fn truncate(&mut self, offset: i64) -> Result<(), IoError> {
let orig_pos = match self.tell() { Ok(i) => i, Err(e) => return Err(e) };
match self.seek(offset, io::SeekSet) {
Ok(_) => {}, Err(e) => return Err(e),
};
let ret = unsafe {
let handle = libc::get_osfhandle(self.fd) as libc::HANDLE;
match libc::SetEndOfFile(handle) {
0 => Err(super::last_error()),
_ => Ok(())
}
};
let _ = self.seek(orig_pos as i64, io::SeekSet);
return ret;
}
#[cfg(unix)]
fn truncate(&mut self, offset: i64) -> Result<(), IoError> {
super::mkerr_libc(retry(|| unsafe {
libc::ftruncate(self.fd, offset as libc::off_t)
}))
}
}
impl rtio::RtioPipe for FileDesc {
fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
self.inner_read(buf)
}
fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
self.inner_write(buf)
}
}
impl rtio::RtioTTY for FileDesc {
fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
self.inner_read(buf)
}
fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
self.inner_write(buf)
}
fn set_raw(&mut self, _raw: bool) -> Result<(), IoError> {
Err(super::unimpl())
}
fn get_winsize(&mut self) -> Result<(int, int), IoError> {
Err(super::unimpl())
}
fn isatty(&self) -> bool { false }
}
impl Drop for FileDesc {
fn drop(&mut self) {
// closing stdio file handles makes no sense, so never do it. Also, note
// that errors are ignored when closing a file descriptor. The reason
// for this is that if an error occurs we don't actually know if the
// file descriptor was closed or not, and if we retried (for something
// like EINTR), we might close another valid file descriptor (opened
// after we closed ours.
if self.close_on_drop && self.fd > libc::STDERR_FILENO {
let n = unsafe { libc::close(self.fd) };
if n != 0 {
warn!("error {} when closing file descriptor {}", n, self.fd);
}
}
}
}
pub struct CFile {
priv file: *libc::FILE,
priv fd: FileDesc,
}
impl CFile {
/// Create a `CFile` from an open `FILE` pointer.
///
/// The `CFile` takes ownership of the `FILE` pointer and will close it upon
/// destruction.
pub fn new(file: *libc::FILE) -> CFile {
CFile {
file: file,
fd: FileDesc::new(unsafe { libc::fileno(file) }, false)
}
}
pub fn flush(&mut self) -> Result<(), IoError> {
super::mkerr_libc(retry(|| unsafe { libc::fflush(self.file) }))
}
}
impl rtio::RtioFileStream for CFile {
fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError> {
let ret = keep_going(buf, |buf, len| {
unsafe {
libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
self.file) as i64
}
});
if ret == 0 {
Err(io::standard_error(io::EndOfFile))
} else if ret < 0 {
Err(super::last_error())
} else {
Ok(ret as int)
}
}
fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
let ret = keep_going(buf, |buf, len| {
unsafe {
libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t,
self.file) as i64
}
});
if ret < 0 {
Err(super::last_error())
} else {
Ok(())
}
}
fn pread(&mut self, buf: &mut [u8], offset: u64) -> Result<int, IoError> {
self.flush().and_then(|()| self.fd.pread(buf, offset))
}
fn pwrite(&mut self, buf: &[u8], offset: u64) -> Result<(), IoError> {
self.flush().and_then(|()| self.fd.pwrite(buf, offset))
}
fn seek(&mut self, pos: i64, style: io::SeekStyle) -> Result<u64, IoError> {
let whence = match style {
io::SeekSet => libc::SEEK_SET,
io::SeekEnd => libc::SEEK_END,
io::SeekCur => libc::SEEK_CUR,
};
let n = unsafe { libc::fseek(self.file, pos as libc::c_long, whence) };
if n < 0 {
Err(super::last_error())
} else {
Ok(n as u64)
}
}
fn tell(&self) -> Result<u64, IoError> {
let ret = unsafe { libc::ftell(self.file) };
if ret < 0 {
Err(super::last_error())
} else {
Ok(ret as u64)
}
}
fn fsync(&mut self) -> Result<(), IoError> {
self.flush().and_then(|()| self.fd.fsync())
}
fn datasync(&mut self) -> Result<(), IoError> {
self.flush().and_then(|()| self.fd.fsync())
}
fn truncate(&mut self, offset: i64) -> Result<(), IoError> {
self.flush().and_then(|()| self.fd.truncate(offset))
}
}
impl Drop for CFile {
fn drop(&mut self) {
unsafe { libc::fclose(self.file); }
}
}
pub fn open(path: &CString, fm: io::FileMode, fa: io::FileAccess)
-> IoResult<FileDesc> {
let flags = match fm {
io::Open => 0,
io::Append => libc::O_APPEND,
io::Truncate => libc::O_TRUNC,
};
// Opening with a write permission must silently create the file.
let (flags, mode) = match fa {
io::Read => (flags | libc::O_RDONLY, 0),
io::Write => (flags | libc::O_WRONLY | libc::O_CREAT,
libc::S_IRUSR | libc::S_IWUSR),
io::ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
libc::S_IRUSR | libc::S_IWUSR),
};
return match os_open(path, flags, mode) {
-1 => Err(super::last_error()),
fd => Ok(FileDesc::new(fd, true)),
};
#[cfg(windows)]
fn os_open(path: &CString, flags: c_int, mode: c_int) -> c_int {
as_utf16_p(path.as_str().unwrap(), |path| {
retry(|| unsafe { libc::wopen(path, flags, mode) })
})
}
#[cfg(unix)]
fn os_open(path: &CString, flags: c_int, mode: c_int) -> c_int {
retry(|| unsafe { libc::open(path.with_ref(|p| p), flags, mode) })
}
}
pub fn mkdir(p: &CString, mode: io::FilePermission) -> IoResult<()> {
return os_mkdir(p, mode as c_int);
#[cfg(windows)]
fn os_mkdir(p: &CString, _mode: c_int) -> IoResult<()> {
super::mkerr_winbool(unsafe {
// FIXME: turn mode into something useful? #2623
as_utf16_p(p.as_str().unwrap(), |buf| {
libc::CreateDirectoryW(buf, ptr::mut_null())
})
})
}
#[cfg(unix)]
fn os_mkdir(p: &CString, mode: c_int) -> IoResult<()> {
super::mkerr_libc(retry(|| unsafe {
libc::mkdir(p.with_ref(|p| p), mode as libc::mode_t)
}))
}
}
pub fn readdir(p: &CString) -> IoResult<~[Path]> {
fn prune(root: &CString, dirs: ~[Path]) -> ~[Path] {
let root = unsafe { CString::new(root.with_ref(|p| p), false) };
let root = Path::new(root);
dirs.move_iter().filter(|path| {
path.as_vec() != bytes!(".") && path.as_vec() != bytes!("..")
}).map(|path| root.join(path)).collect()
}
unsafe {
#[cfg(not(windows))]
unsafe fn get_list(p: &CString) -> IoResult<~[Path]> {
use std::libc::{dirent_t};
use std::libc::{opendir, readdir, closedir};
extern {
fn rust_list_dir_val(ptr: *dirent_t) -> *libc::c_char;
}
debug!("os::list_dir -- BEFORE OPENDIR");
let dir_ptr = p.with_ref(|buf| opendir(buf));
if dir_ptr as uint != 0 {
let mut paths = ~[];
debug!("os::list_dir -- opendir() SUCCESS");
let mut entry_ptr = readdir(dir_ptr);
while entry_ptr as uint != 0 {
let cstr = CString::new(rust_list_dir_val(entry_ptr), false);
paths.push(Path::new(cstr));
entry_ptr = readdir(dir_ptr);
}
closedir(dir_ptr);
Ok(paths)
} else {
Err(super::last_error())
}
}
#[cfg(windows)]
unsafe fn get_list(p: &CString) -> IoResult<~[Path]> {
use std::libc::consts::os::extra::INVALID_HANDLE_VALUE;
use std::libc::{wcslen, free};
use std::libc::funcs::extra::kernel32::{
FindFirstFileW,
FindNextFileW,
FindClose,
};
use std::libc::types::os::arch::extra::HANDLE;
use os::win32::{
as_utf16_p
};
use rt::global_heap::malloc_raw;
#[nolink]
extern {
fn rust_list_dir_wfd_size() -> libc::size_t;
fn rust_list_dir_wfd_fp_buf(wfd: *libc::c_void) -> *u16;
}
let p = CString::new(p.with_ref(|p| p), false);
let p = Path::new(p);
let star = p.join("*");
as_utf16_p(star.as_str().unwrap(), |path_ptr| {
let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint);
let find_handle = FindFirstFileW(path_ptr, wfd_ptr as HANDLE);
if find_handle as libc::c_int != INVALID_HANDLE_VALUE {
let mut paths = ~[];
let mut more_files = 1 as libc::c_int;
while more_files != 0 {
let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr as *c_void);
if fp_buf as uint == 0 {
fail!("os::list_dir() failure: got null ptr from wfd");
}
else {
let fp_vec = vec::from_buf(
fp_buf, wcslen(fp_buf) as uint);
let fp_str = str::from_utf16(fp_vec);
paths.push(Path::new(fp_str));
}
more_files = FindNextFileW(find_handle, wfd_ptr as HANDLE);
}
FindClose(find_handle);
free(wfd_ptr as *mut c_void);
Ok(paths)
} else {
Err(super::last_error())
}
})
}
get_list(p).map(|paths| prune(p, paths))
}
}
pub fn unlink(p: &CString) -> IoResult<()> {
return os_unlink(p);
#[cfg(windows)]
fn os_unlink(p: &CString) -> IoResult<()> {
super::mkerr_winbool(unsafe {
as_utf16_p(p.as_str().unwrap(), |buf| {
libc::DeleteFileW(buf)
})
})
}
#[cfg(unix)]
fn os_unlink(p: &CString) -> IoResult<()> {
super::mkerr_libc(retry(|| unsafe { libc::unlink(p.with_ref(|p| p)) }))
}
}
pub fn rename(old: &CString, new: &CString) -> IoResult<()> {
return os_rename(old, new);
#[cfg(windows)]
fn os_rename(old: &CString, new: &CString) -> IoResult<()> {
super::mkerr_winbool(unsafe {
as_utf16_p(old.as_str().unwrap(), |old| {
as_utf16_p(new.as_str().unwrap(), |new| {
libc::MoveFileExW(old, new, libc::MOVEFILE_REPLACE_EXISTING)
})
})
})
}
#[cfg(unix)]
fn os_rename(old: &CString, new: &CString) -> IoResult<()> {
super::mkerr_libc(retry(|| unsafe {
libc::rename(old.with_ref(|p| p), new.with_ref(|p| p))
}))
}
}
pub fn chmod(p: &CString, mode: io::FilePermission) -> IoResult<()> {
return super::mkerr_libc(os_chmod(p, mode as c_int));
#[cfg(windows)]
fn os_chmod(p: &CString, mode: c_int) -> c_int {
unsafe {
as_utf16_p(p.as_str().unwrap(), |p| retry(|| {
libc::wchmod(p, mode)
}))
}
}
#[cfg(unix)]
fn os_chmod(p: &CString, mode: c_int) -> c_int {
retry(||unsafe { libc::chmod(p.with_ref(|p| p), mode as libc::mode_t) })
}
}
pub fn rmdir(p: &CString) -> IoResult<()> {
return super::mkerr_libc(os_rmdir(p));
#[cfg(windows)]
fn os_rmdir(p: &CString) -> c_int {
unsafe {
as_utf16_p(p.as_str().unwrap(), |p| retry(|| {
libc::wrmdir(p)
}))
}
}
#[cfg(unix)]
fn os_rmdir(p: &CString) -> c_int {
retry(|| unsafe { libc::rmdir(p.with_ref(|p| p)) })
}
}
pub fn chown(p: &CString, uid: int, gid: int) -> IoResult<()> {
return super::mkerr_libc(os_chown(p, uid, gid));
// libuv has this as a no-op, so seems like this should as well?
#[cfg(windows)]
fn os_chown(_p: &CString, _uid: int, _gid: int) -> c_int { 0 }
#[cfg(unix)]
fn os_chown(p: &CString, uid: int, gid: int) -> c_int {
retry(|| unsafe {
libc::chown(p.with_ref(|p| p), uid as libc::uid_t,
gid as libc::gid_t)
})
}
}
pub fn readlink(p: &CString) -> IoResult<Path> {
return os_readlink(p);
// FIXME: I have a feeling that this reads intermediate symlinks as well.
#[cfg(windows)]
fn os_readlink(p: &CString) -> IoResult<Path> {
let handle = unsafe {
as_utf16_p(p.as_str().unwrap(), |p| {
libc::CreateFileW(p,
libc::GENERIC_READ,
libc::FILE_SHARE_READ,
ptr::mut_null(),
libc::OPEN_EXISTING,
libc::FILE_ATTRIBUTE_NORMAL,
ptr::mut_null())
})
};
if handle == ptr::mut_null() { return Err(super::last_error()) }
let ret = fill_utf16_buf_and_decode(|buf, sz| {
unsafe {
libc::GetFinalPathNameByHandleW(handle, buf as *u16, sz,
libc::VOLUME_NAME_NT)
}
});
let ret = match ret {
Some(s) => Ok(Path::new(s)),
None => Err(super::last_error()),
};
unsafe { libc::CloseHandle(handle) };
return ret;
}
#[cfg(unix)]
fn os_readlink(p: &CString) -> IoResult<Path> {
let p = p.with_ref(|p| p);
let mut len = unsafe { libc::pathconf(p, libc::_PC_NAME_MAX) };
if len == -1 {
len = 1024; // FIXME: read PATH_MAX from C ffi?
}
let mut buf = vec::with_capacity::<u8>(len as uint);
match retry(|| unsafe {
libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
len as libc::size_t) as libc::c_int
}) {
-1 => Err(super::last_error()),
n => {
assert!(n > 0);
unsafe { buf.set_len(n as uint); }
Ok(Path::new(buf))
}
}
}
}
pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> {
return os_symlink(src, dst);
#[cfg(windows)]
fn os_symlink(src: &CString, dst: &CString) -> IoResult<()> {
super::mkerr_winbool(as_utf16_p(src.as_str().unwrap(), |src| {
as_utf16_p(dst.as_str().unwrap(), |dst| {
unsafe { libc::CreateSymbolicLinkW(dst, src, 0) }
})
}))
}
#[cfg(unix)]
fn os_symlink(src: &CString, dst: &CString) -> IoResult<()> {
super::mkerr_libc(retry(|| unsafe {
libc::symlink(src.with_ref(|p| p), dst.with_ref(|p| p))
}))
}
}
pub fn link(src: &CString, dst: &CString) -> IoResult<()> {
return os_link(src, dst);
#[cfg(windows)]
fn os_link(src: &CString, dst: &CString) -> IoResult<()> {
super::mkerr_winbool(as_utf16_p(src.as_str().unwrap(), |src| {
as_utf16_p(dst.as_str().unwrap(), |dst| {
unsafe { libc::CreateHardLinkW(dst, src, ptr::mut_null()) }
})
}))
}
#[cfg(unix)]
fn os_link(src: &CString, dst: &CString) -> IoResult<()> {
super::mkerr_libc(retry(|| unsafe {
libc::link(src.with_ref(|p| p), dst.with_ref(|p| p))
}))
}
}
#[cfg(windows)]
fn mkstat(stat: &libc::stat, path: &CString) -> io::FileStat {
let path = unsafe { CString::new(path.with_ref(|p| p), false) };
let kind = match (stat.st_mode as c_int) & libc::S_IFMT {
libc::S_IFREG => io::TypeFile,
libc::S_IFDIR => io::TypeDirectory,
libc::S_IFIFO => io::TypeNamedPipe,
libc::S_IFBLK => io::TypeBlockSpecial,
libc::S_IFLNK => io::TypeSymlink,
_ => io::TypeUnknown,
};
io::FileStat {
path: Path::new(path),
size: stat.st_size as u64,
kind: kind,
perm: (stat.st_mode) as io::FilePermission & io::AllPermissions,
created: stat.st_ctime as u64,
modified: stat.st_mtime as u64,
accessed: stat.st_atime as u64,
unstable: io::UnstableFileStat {
device: stat.st_dev as u64,
inode: stat.st_ino as u64,
rdev: stat.st_rdev as u64,
nlink: stat.st_nlink as u64,
uid: stat.st_uid as u64,
gid: stat.st_gid as u64,
blksize: 0,
blocks: 0,
flags: 0,
gen: 0,
}
}
}
#[cfg(unix)]
fn mkstat(stat: &libc::stat, path: &CString) -> io::FileStat {
let path = unsafe { CString::new(path.with_ref(|p| p), false) };
// FileStat times are in milliseconds
fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
let kind = match (stat.st_mode as c_int) & libc::S_IFMT {
libc::S_IFREG => io::TypeFile,
libc::S_IFDIR => io::TypeDirectory,
libc::S_IFIFO => io::TypeNamedPipe,
libc::S_IFBLK => io::TypeBlockSpecial,
libc::S_IFLNK => io::TypeSymlink,
_ => io::TypeUnknown,
};
#[cfg(not(target_os = "linux"), not(target_os = "android"))]
fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
#[cfg(target_os = "linux")] #[cfg(target_os = "android")]
fn flags(_stat: &libc::stat) -> u64 { 0 }
#[cfg(not(target_os = "linux"), not(target_os = "android"))]
fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
#[cfg(target_os = "linux")] #[cfg(target_os = "android")]
fn gen(_stat: &libc::stat) -> u64 { 0 }
io::FileStat {
path: Path::new(path),
size: stat.st_size as u64,
kind: kind,
perm: (stat.st_mode) as io::FilePermission & io::AllPermissions,
created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
unstable: io::UnstableFileStat {
device: stat.st_dev as u64,
inode: stat.st_ino as u64,
rdev: stat.st_rdev as u64,
nlink: stat.st_nlink as u64,
uid: stat.st_uid as u64,
gid: stat.st_gid as u64,
blksize: stat.st_blksize as u64,
blocks: stat.st_blocks as u64,
flags: flags(stat),
gen: gen(stat),
}
}
}
pub fn stat(p: &CString) -> IoResult<io::FileStat> {
return os_stat(p);
#[cfg(windows)]
fn os_stat(p: &CString) -> IoResult<io::FileStat> {
let mut stat: libc::stat = unsafe { intrinsics::uninit() };
as_utf16_p(p.as_str().unwrap(), |up| {
match retry(|| unsafe { libc::wstat(up, &mut stat) }) {
0 => Ok(mkstat(&stat, p)),
_ => Err(super::last_error()),
}
})
}
#[cfg(unix)]
fn os_stat(p: &CString) -> IoResult<io::FileStat> {
let mut stat: libc::stat = unsafe { intrinsics::uninit() };
match retry(|| unsafe { libc::stat(p.with_ref(|p| p), &mut stat) }) {
0 => Ok(mkstat(&stat, p)),
_ => Err(super::last_error()),
}
}
}
pub fn lstat(p: &CString) -> IoResult<io::FileStat> {
return os_lstat(p);
// FIXME: windows implementation is missing
#[cfg(windows)]
fn os_lstat(_p: &CString) -> IoResult<io::FileStat> {
Err(super::unimpl())
}
#[cfg(unix)]
fn os_lstat(p: &CString) -> IoResult<io::FileStat> {
let mut stat: libc::stat = unsafe { intrinsics::uninit() };
match retry(|| unsafe { libc::lstat(p.with_ref(|p| p), &mut stat) }) {
0 => Ok(mkstat(&stat, p)),
_ => Err(super::last_error()),
}
}
}
pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> {
return super::mkerr_libc(os_utime(p, atime, mtime));
#[cfg(windows)]
fn os_utime(p: &CString, atime: u64, mtime: u64) -> c_int {
let buf = libc::utimbuf {
actime: (atime / 1000) as libc::time64_t,
modtime: (mtime / 1000) as libc::time64_t,
};
unsafe {
as_utf16_p(p.as_str().unwrap(), |p| retry(|| {
libc::wutime(p, &buf)
}))
}
}
#[cfg(unix)]
fn os_utime(p: &CString, atime: u64, mtime: u64) -> c_int {
let buf = libc::utimbuf {
actime: (atime / 1000) as libc::time_t,
modtime: (mtime / 1000) as libc::time_t,
};
retry(|| unsafe { libc::utime(p.with_ref(|p| p), &buf) })
}
}
#[cfg(test)]
mod tests {
use super::{CFile, FileDesc};
use std::io;
use std::libc;
use std::os;
use std::rt::rtio::RtioFileStream;
#[ignore(cfg(target_os = "freebsd"))] // hmm, maybe pipes have a tiny buffer
#[test]
fn test_file_desc() {
// Run this test with some pipes so we don't have to mess around with
// opening or closing files.
unsafe {
let os::Pipe { input, out } = os::pipe();
let mut reader = FileDesc::new(input, true);
let mut writer = FileDesc::new(out, true);
writer.inner_write(bytes!("test"));
let mut buf = [0u8, ..4];
match reader.inner_read(buf) {
Ok(4) => {
assert_eq!(buf[0], 't' as u8);
assert_eq!(buf[1], 'e' as u8);
assert_eq!(buf[2], 's' as u8);
assert_eq!(buf[3], 't' as u8);
}
r => fail!("invalid read: {:?}", r)
}
assert!(writer.inner_read(buf).is_err());
assert!(reader.inner_write(buf).is_err());
}
}
#[ignore(cfg(windows))] // apparently windows doesn't like tmpfile
#[test]
fn test_cfile() {
unsafe {
let f = libc::tmpfile();
assert!(!f.is_null());
let mut file = CFile::new(f);
file.write(bytes!("test"));
let mut buf = [0u8, ..4];
file.seek(0, io::SeekSet);
match file.read(buf) {
Ok(4) => {
assert_eq!(buf[0], 't' as u8);
assert_eq!(buf[1], 'e' as u8);
assert_eq!(buf[2], 's' as u8);
assert_eq!(buf[3], 't' as u8);
}
r => fail!("invalid read: {:?}", r)
}
}
}
}