/
os.rs
1622 lines (1434 loc) · 45.5 KB
/
os.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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-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.
/*!
* Higher-level interfaces to libc::* functions and operating system services.
*
* In general these take and return rust types, use rust idioms (enums,
* closures, vectors) rather than C idioms, and do more extensive safety
* checks.
*
* This module is not meant to only contain 1:1 mappings to libc entries; any
* os-interface code that is reasonably useful and broadly applicable can go
* here. Including utility routines that merely build on other os code.
*
* We assume the general case is that users do not care, and do not want to
* be made to care, which operating system they are on. While they may want
* to special case various special cases -- and so we will not _hide_ the
* facts of which OS the user is on -- they should be given the opportunity
* to write OS-ignorant code by default.
*/
use cast;
use io;
use libc;
use libc::{c_char, c_void, c_int, size_t};
use libc::{mode_t, FILE};
use option;
use option::{Some, None};
use prelude::*;
use ptr;
use str;
use task;
use uint;
use unstable::finally::Finally;
use vec;
pub use libc::fclose;
pub use os::consts::*;
pub fn close(fd: c_int) -> c_int {
unsafe {
libc::close(fd)
}
}
pub mod rustrt {
use libc::{c_char, c_int};
use libc;
pub extern {
unsafe fn rust_get_argc() -> c_int;
unsafe fn rust_get_argv() -> **c_char;
unsafe fn rust_path_is_dir(path: *libc::c_char) -> c_int;
unsafe fn rust_path_exists(path: *libc::c_char) -> c_int;
unsafe fn rust_set_exit_status(code: libc::intptr_t);
}
}
pub static TMPBUF_SZ : uint = 1000u;
static BUF_BYTES : uint = 2048u;
pub fn getcwd() -> Path {
let buf = [0 as libc::c_char, ..BUF_BYTES];
unsafe {
if(0 as *libc::c_char == libc::getcwd(
&buf[0],
BUF_BYTES as libc::size_t)) {
fail!();
}
Path(str::raw::from_c_str(&buf[0]))
}
}
// FIXME: move these to str perhaps? #2620
pub fn as_c_charp<T>(s: &str, f: &fn(*c_char) -> T) -> T {
str::as_c_str(s, |b| f(b as *c_char))
}
pub fn fill_charp_buf(f: &fn(*mut c_char, size_t) -> bool)
-> Option<~str> {
let mut buf = vec::from_elem(TMPBUF_SZ, 0u8 as c_char);
do vec::as_mut_buf(buf) |b, sz| {
if f(b, sz as size_t) {
unsafe {
Some(str::raw::from_buf(b as *u8))
}
} else {
None
}
}
}
#[cfg(windows)]
pub mod win32 {
use libc;
use vec;
use str;
use option::{None, Option};
use option;
use os::TMPBUF_SZ;
use libc::types::os::arch::extra::DWORD;
pub fn fill_utf16_buf_and_decode(f: &fn(*mut u16, DWORD) -> DWORD)
-> Option<~str> {
unsafe {
let mut n = TMPBUF_SZ as DWORD;
let mut res = None;
let mut done = false;
while !done {
let mut k: DWORD = 0;
let mut buf = vec::from_elem(n as uint, 0u16);
do vec::as_mut_buf(buf) |b, _sz| {
k = f(b, TMPBUF_SZ as DWORD);
if k == (0 as DWORD) {
done = true;
} else if (k == n &&
libc::GetLastError() ==
libc::ERROR_INSUFFICIENT_BUFFER as DWORD) {
n *= (2 as DWORD);
} else {
done = true;
}
}
if k != 0 && done {
let sub = vec::slice(buf, 0u, k as uint);
res = option::Some(str::from_utf16(sub));
}
}
return res;
}
}
pub fn as_utf16_p<T>(s: &str, f: &fn(*u16) -> T) -> T {
let mut t = str::to_utf16(s);
// Null terminate before passing on.
t += ~[0u16];
vec::as_imm_buf(t, |buf, _len| f(buf))
}
}
/*
Accessing environment variables is not generally threadsafe.
This uses a per-runtime lock to serialize access.
FIXME #4726: It would probably be appropriate to make this a real global
*/
fn with_env_lock<T>(f: &fn() -> T) -> T {
use unstable::global::global_data_clone_create;
use unstable::{Exclusive, exclusive};
struct SharedValue(());
type ValueMutex = Exclusive<SharedValue>;
fn key(_: ValueMutex) { }
unsafe {
let lock: ValueMutex = global_data_clone_create(key, || {
~exclusive(SharedValue(()))
});
lock.with_imm(|_| f() )
}
}
pub fn env() -> ~[(~str,~str)] {
unsafe {
#[cfg(windows)]
unsafe fn get_env_pairs() -> ~[~str] {
use libc::types::os::arch::extra::LPTCH;
use libc::funcs::extra::kernel32::{
GetEnvironmentStringsA,
FreeEnvironmentStringsA
};
let ch = GetEnvironmentStringsA();
if (ch as uint == 0) {
fail!(fmt!("os::env() failure getting env string from OS: %s",
os::last_os_error()));
}
let mut curr_ptr: uint = ch as uint;
let mut result = ~[];
while(*(curr_ptr as *libc::c_char) != 0 as libc::c_char) {
let env_pair = str::raw::from_c_str(
curr_ptr as *libc::c_char);
result.push(env_pair);
curr_ptr +=
libc::strlen(curr_ptr as *libc::c_char) as uint
+ 1;
}
FreeEnvironmentStringsA(ch);
result
}
#[cfg(unix)]
unsafe fn get_env_pairs() -> ~[~str] {
extern mod rustrt {
unsafe fn rust_env_pairs() -> **libc::c_char;
}
let environ = rustrt::rust_env_pairs();
if (environ as uint == 0) {
fail!(fmt!("os::env() failure getting env string from OS: %s",
os::last_os_error()));
}
let mut result = ~[];
ptr::array_each(environ, |e| {
let env_pair = str::raw::from_c_str(e);
debug!("get_env_pairs: %s",
env_pair);
result.push(env_pair);
});
result
}
fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
let mut pairs = ~[];
for input.each |p| {
let mut vs = ~[];
for str::each_splitn_char(*p, '=', 1) |s| { vs.push(s.to_owned()) }
debug!("splitting: len: %u",
vs.len());
assert!(vs.len() == 2);
pairs.push((copy vs[0], copy vs[1]));
}
pairs
}
do with_env_lock {
let unparsed_environ = get_env_pairs();
env_convert(unparsed_environ)
}
}
}
#[cfg(unix)]
pub fn getenv(n: &str) -> Option<~str> {
unsafe {
do with_env_lock {
let s = str::as_c_str(n, |s| libc::getenv(s));
if ptr::null::<u8>() == cast::transmute(s) {
option::None::<~str>
} else {
let s = cast::transmute(s);
option::Some::<~str>(str::raw::from_buf(s))
}
}
}
}
#[cfg(windows)]
pub fn getenv(n: &str) -> Option<~str> {
unsafe {
do with_env_lock {
use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
do as_utf16_p(n) |u| {
do fill_utf16_buf_and_decode() |buf, sz| {
libc::GetEnvironmentVariableW(u, buf, sz)
}
}
}
}
}
#[cfg(unix)]
pub fn setenv(n: &str, v: &str) {
unsafe {
do with_env_lock {
do str::as_c_str(n) |nbuf| {
do str::as_c_str(v) |vbuf| {
libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
}
}
}
}
}
#[cfg(windows)]
pub fn setenv(n: &str, v: &str) {
unsafe {
do with_env_lock {
use os::win32::as_utf16_p;
do as_utf16_p(n) |nbuf| {
do as_utf16_p(v) |vbuf| {
libc::SetEnvironmentVariableW(nbuf, vbuf);
}
}
}
}
}
pub fn fdopen(fd: c_int) -> *FILE {
unsafe {
return do as_c_charp("r") |modebuf| {
libc::fdopen(fd, modebuf)
};
}
}
// fsync related
#[cfg(windows)]
pub fn fsync_fd(fd: c_int, _level: io::fsync::Level) -> c_int {
unsafe {
use libc::funcs::extra::msvcrt::*;
return commit(fd);
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
unsafe {
use libc::funcs::posix01::unistd::*;
match level {
io::fsync::FSync
| io::fsync::FullFSync => return fsync(fd),
io::fsync::FDataSync => return fdatasync(fd)
}
}
}
#[cfg(target_os = "macos")]
pub fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
unsafe {
use libc::consts::os::extra::*;
use libc::funcs::posix88::fcntl::*;
use libc::funcs::posix01::unistd::*;
match level {
io::fsync::FSync => return fsync(fd),
_ => {
// According to man fnctl, the ok retval is only specified to be
// !=-1
if (fcntl(F_FULLFSYNC as c_int, fd) == -1 as c_int)
{ return -1 as c_int; }
else
{ return 0 as c_int; }
}
}
}
}
#[cfg(target_os = "freebsd")]
pub fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int {
unsafe {
use libc::funcs::posix01::unistd::*;
return fsync(fd);
}
}
pub struct Pipe { mut in: c_int, mut out: c_int }
#[cfg(unix)]
pub fn pipe() -> Pipe {
unsafe {
let mut fds = Pipe {in: 0 as c_int,
out: 0 as c_int };
assert!((libc::pipe(&mut fds.in) == (0 as c_int)));
return Pipe {in: fds.in, out: fds.out};
}
}
#[cfg(windows)]
pub fn pipe() -> Pipe {
unsafe {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in core::run.
let mut fds = Pipe {in: 0 as c_int,
out: 0 as c_int };
let res = libc::pipe(&mut fds.in, 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int);
assert!((res == 0 as c_int));
assert!((fds.in != -1 as c_int && fds.in != 0 as c_int));
assert!((fds.out != -1 as c_int && fds.in != 0 as c_int));
return Pipe {in: fds.in, out: fds.out};
}
}
fn dup2(src: c_int, dst: c_int) -> c_int {
unsafe {
libc::dup2(src, dst)
}
}
pub fn dll_filename(base: &str) -> ~str {
return str::from_slice(DLL_PREFIX) + str::from_slice(base) +
str::from_slice(DLL_SUFFIX)
}
pub fn self_exe_path() -> Option<Path> {
#[cfg(target_os = "freebsd")]
fn load_self() -> Option<~str> {
unsafe {
use libc::funcs::bsd44::*;
use libc::consts::os::extra::*;
do fill_charp_buf() |buf, sz| {
let mib = ~[CTL_KERN as c_int,
KERN_PROC as c_int,
KERN_PROC_PATHNAME as c_int, -1 as c_int];
let mut sz = sz;
sysctl(vec::raw::to_ptr(mib), vec::len(mib) as ::libc::c_uint,
buf as *mut c_void, &mut sz, ptr::null(),
0u as size_t) == (0 as c_int)
}
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
fn load_self() -> Option<~str> {
unsafe {
use libc::funcs::posix01::unistd::readlink;
let mut path_str = str::with_capacity(TMPBUF_SZ);
let len = do str::as_c_str(path_str) |buf| {
let buf = buf as *mut c_char;
do as_c_charp("/proc/self/exe") |proc_self_buf| {
readlink(proc_self_buf, buf, TMPBUF_SZ as size_t)
}
};
if len == -1 {
None
} else {
str::raw::set_len(&mut path_str, len as uint);
Some(path_str)
}
}
}
#[cfg(target_os = "macos")]
fn load_self() -> Option<~str> {
unsafe {
do fill_charp_buf() |buf, sz| {
let mut sz = sz as u32;
libc::funcs::extra::_NSGetExecutablePath(
buf, &mut sz) == (0 as c_int)
}
}
}
#[cfg(windows)]
fn load_self() -> Option<~str> {
unsafe {
use os::win32::fill_utf16_buf_and_decode;
do fill_utf16_buf_and_decode() |buf, sz| {
libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
}
}
}
do load_self().map |pth| {
Path(*pth).dir_path()
}
}
/**
* Returns the path to the user's home directory, if known.
*
* On Unix, returns the value of the 'HOME' environment variable if it is set
* and not equal to the empty string.
*
* On Windows, returns the value of the 'HOME' environment variable if it is
* set and not equal to the empty string. Otherwise, returns the value of the
* 'USERPROFILE' environment variable if it is set and not equal to the empty
* string.
*
* Otherwise, homedir returns option::none.
*/
pub fn homedir() -> Option<Path> {
return match getenv(~"HOME") {
Some(ref p) => if !str::is_empty(*p) {
Some(Path(*p))
} else {
secondary()
},
None => secondary()
};
#[cfg(unix)]
fn secondary() -> Option<Path> {
None
}
#[cfg(windows)]
fn secondary() -> Option<Path> {
do getenv(~"USERPROFILE").chain |p| {
if !str::is_empty(p) {
Some(Path(p))
} else {
None
}
}
}
}
/**
* Returns the path to a temporary directory.
*
* On Unix, returns the value of the 'TMPDIR' environment variable if it is
* set and non-empty and '/tmp' otherwise.
*
* On Windows, returns the value of, in order, the 'TMP', 'TEMP',
* 'USERPROFILE' environment variable if any are set and not the empty
* string. Otherwise, tmpdir returns the path to the Windows directory.
*/
pub fn tmpdir() -> Path {
return lookup();
fn getenv_nonempty(v: &str) -> Option<Path> {
match getenv(v) {
Some(x) =>
if str::is_empty(x) {
None
} else {
Some(Path(x))
},
_ => None
}
}
#[cfg(unix)]
#[allow(non_implicitly_copyable_typarams)]
fn lookup() -> Path {
getenv_nonempty("TMPDIR").get_or_default(Path("/tmp"))
}
#[cfg(windows)]
#[allow(non_implicitly_copyable_typarams)]
fn lookup() -> Path {
getenv_nonempty("TMP").or(
getenv_nonempty("TEMP").or(
getenv_nonempty("USERPROFILE").or(
getenv_nonempty("WINDIR")))).get_or_default(Path("C:\\Windows"))
}
}
/// Recursively walk a directory structure
pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) {
walk_dir_(p, f);
fn walk_dir_(p: &Path, f: &fn(&Path) -> bool) -> bool {
let mut keepgoing = true;
do list_dir(p).each |q| {
let path = &p.push(*q);
if !f(path) {
keepgoing = false;
false
} else {
if path_is_dir(path) {
if !walk_dir_(path, f) {
keepgoing = false;
false
} else {
true
}
} else {
true
}
}
}
return keepgoing;
}
}
/// Indicates whether a path represents a directory
pub fn path_is_dir(p: &Path) -> bool {
unsafe {
do str::as_c_str(p.to_str()) |buf| {
rustrt::rust_path_is_dir(buf) != 0 as c_int
}
}
}
/// Indicates whether a path exists
pub fn path_exists(p: &Path) -> bool {
unsafe {
do str::as_c_str(p.to_str()) |buf| {
rustrt::rust_path_exists(buf) != 0 as c_int
}
}
}
/**
* Convert a relative path to an absolute path
*
* If the given path is relative, return it prepended with the current working
* directory. If the given path is already an absolute path, return it
* as is.
*/
// NB: this is here rather than in path because it is a form of environment
// querying; what it does depends on the process working directory, not just
// the input paths.
pub fn make_absolute(p: &Path) -> Path {
if p.is_absolute {
copy *p
} else {
getcwd().push_many(p.components)
}
}
/// Creates a directory at the specified path
pub fn make_dir(p: &Path, mode: c_int) -> bool {
return mkdir(p, mode);
#[cfg(windows)]
fn mkdir(p: &Path, _mode: c_int) -> bool {
unsafe {
use os::win32::as_utf16_p;
// FIXME: turn mode into something useful? #2623
do as_utf16_p(p.to_str()) |buf| {
libc::CreateDirectoryW(buf, unsafe {
cast::transmute(0)
})
!= (0 as libc::BOOL)
}
}
}
#[cfg(unix)]
fn mkdir(p: &Path, mode: c_int) -> bool {
unsafe {
do as_c_charp(p.to_str()) |c| {
libc::mkdir(c, mode as mode_t) == (0 as c_int)
}
}
}
}
/// Creates a directory with a given mode.
/// Returns true iff creation
/// succeeded. Also creates all intermediate subdirectories
/// if they don't already exist, giving all of them the same mode.
// tjc: if directory exists but with different permissions,
// should we return false?
pub fn mkdir_recursive(p: &Path, mode: c_int) -> bool {
if path_is_dir(p) {
return true;
}
else if p.components.is_empty() {
return false;
}
else if p.components.len() == 1 {
// No parent directories to create
path_is_dir(p) || make_dir(p, mode)
}
else {
mkdir_recursive(&p.pop(), mode) && make_dir(p, mode)
}
}
/// Lists the contents of a directory
#[allow(non_implicitly_copyable_typarams)]
pub fn list_dir(p: &Path) -> ~[~str] {
unsafe {
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[cfg(target_os = "freebsd")]
#[cfg(target_os = "macos")]
unsafe fn get_list(p: &Path) -> ~[~str] {
use libc::{dirent_t};
use libc::{opendir, readdir, closedir};
extern mod rustrt {
unsafe fn rust_list_dir_val(ptr: *dirent_t)
-> *libc::c_char;
}
let input = p.to_str();
let mut strings = ~[];
let input_ptr = ::cast::transmute(&input[0]);
debug!("os::list_dir -- BEFORE OPENDIR");
let dir_ptr = opendir(input_ptr);
if (dir_ptr as uint != 0) {
debug!("os::list_dir -- opendir() SUCCESS");
let mut entry_ptr = readdir(dir_ptr);
while (entry_ptr as uint != 0) {
strings.push(
str::raw::from_c_str(
rustrt::rust_list_dir_val(
entry_ptr)));
entry_ptr = readdir(dir_ptr);
}
closedir(dir_ptr);
}
else {
debug!("os::list_dir -- opendir() FAILURE");
}
debug!(
"os::list_dir -- AFTER -- #: %?",
strings.len());
strings
}
#[cfg(windows)]
unsafe fn get_list(p: &Path) -> ~[~str] {
use libc::types::os::arch::extra::{LPCTSTR, HANDLE, BOOL};
use libc::consts::os::extra::INVALID_HANDLE_VALUE;
use libc::wcslen;
use libc::funcs::extra::kernel32::{
FindFirstFileW,
FindNextFileW,
FindClose,
};
use os::win32::{
as_utf16_p
};
use unstable::exchange_alloc::{malloc_raw, free_raw};
#[nolink]
extern mod rustrt {
unsafe fn rust_list_dir_wfd_size() -> libc::size_t;
unsafe fn rust_list_dir_wfd_fp_buf(wfd: *libc::c_void)
-> *u16;
}
fn star(p: &Path) -> Path { p.push("*") }
do as_utf16_p(star(p).to_str()) |path_ptr| {
let mut strings = ~[];
let wfd_ptr = malloc_raw(
rustrt::rust_list_dir_wfd_size() as uint);
let find_handle =
FindFirstFileW(
path_ptr,
::cast::transmute(wfd_ptr));
if find_handle as int != INVALID_HANDLE_VALUE {
let mut more_files = 1 as libc::c_int;
while more_files != 0 {
let fp_buf = rustrt::rust_list_dir_wfd_fp_buf(
wfd_ptr);
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);
strings.push(fp_str);
}
more_files = FindNextFileW(
find_handle,
::cast::transmute(wfd_ptr));
}
FindClose(find_handle);
free_raw(wfd_ptr);
}
strings
}
}
do get_list(p).filtered |filename| {
*filename != ~"." && *filename != ~".."
}
}
}
/**
* Lists the contents of a directory
*
* This version prepends each entry with the directory.
*/
pub fn list_dir_path(p: &Path) -> ~[~Path] {
list_dir(p).map(|f| ~p.push(*f))
}
/// Removes a directory at the specified path
pub fn remove_dir(p: &Path) -> bool {
return rmdir(p);
#[cfg(windows)]
fn rmdir(p: &Path) -> bool {
unsafe {
use os::win32::as_utf16_p;
return do as_utf16_p(p.to_str()) |buf| {
libc::RemoveDirectoryW(buf) != (0 as libc::BOOL)
};
}
}
#[cfg(unix)]
fn rmdir(p: &Path) -> bool {
unsafe {
return do as_c_charp(p.to_str()) |buf| {
libc::rmdir(buf) == (0 as c_int)
};
}
}
}
pub fn change_dir(p: &Path) -> bool {
return chdir(p);
#[cfg(windows)]
fn chdir(p: &Path) -> bool {
unsafe {
use os::win32::as_utf16_p;
return do as_utf16_p(p.to_str()) |buf| {
libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
};
}
}
#[cfg(unix)]
fn chdir(p: &Path) -> bool {
unsafe {
return do as_c_charp(p.to_str()) |buf| {
libc::chdir(buf) == (0 as c_int)
};
}
}
}
/// Changes the current working directory to the specified
/// path while acquiring a global lock, then calls `action`.
/// If the change is successful, releases the lock and restores the
/// CWD to what it was before, returning true.
/// Returns false if the directory doesn't exist or if the directory change
/// is otherwise unsuccessful.
pub fn change_dir_locked(p: &Path, action: &fn()) -> bool {
use unstable::global::global_data_clone_create;
use unstable::{Exclusive, exclusive};
fn key(_: Exclusive<()>) { }
let result = unsafe {
global_data_clone_create(key, || {
~exclusive(())
})
};
do result.with_imm() |_| {
let old_dir = os::getcwd();
if change_dir(p) {
action();
change_dir(&old_dir)
}
else {
false
}
}
}
/// Copies a file from one location to another
pub fn copy_file(from: &Path, to: &Path) -> bool {
return do_copy_file(from, to);
#[cfg(windows)]
fn do_copy_file(from: &Path, to: &Path) -> bool {
unsafe {
use os::win32::as_utf16_p;
return do as_utf16_p(from.to_str()) |fromp| {
do as_utf16_p(to.to_str()) |top| {
libc::CopyFileW(fromp, top, (0 as libc::BOOL)) !=
(0 as libc::BOOL)
}
}
}
}
#[cfg(unix)]
fn do_copy_file(from: &Path, to: &Path) -> bool {
unsafe {
let istream = do as_c_charp(from.to_str()) |fromp| {
do as_c_charp("rb") |modebuf| {
libc::fopen(fromp, modebuf)
}
};
if istream as uint == 0u {
return false;
}
let ostream = do as_c_charp(to.to_str()) |top| {
do as_c_charp("w+b") |modebuf| {
libc::fopen(top, modebuf)
}
};
if ostream as uint == 0u {
fclose(istream);
return false;
}
let bufsize = 8192u;
let mut buf = vec::with_capacity::<u8>(bufsize);
let mut done = false;
let mut ok = true;
while !done {
do vec::as_mut_buf(buf) |b, _sz| {
let nread = libc::fread(b as *mut c_void, 1u as size_t,
bufsize as size_t,
istream);
if nread > 0 as size_t {
if libc::fwrite(b as *c_void, 1u as size_t, nread,
ostream) != nread {
ok = false;
done = true;
}
} else {
done = true;
}
}
}
fclose(istream);
fclose(ostream);
return ok;
}
}
}
/// Deletes an existing file
pub fn remove_file(p: &Path) -> bool {
return unlink(p);
#[cfg(windows)]
fn unlink(p: &Path) -> bool {
unsafe {
use os::win32::as_utf16_p;
return do as_utf16_p(p.to_str()) |buf| {
libc::DeleteFileW(buf) != (0 as libc::BOOL)
};
}
}
#[cfg(unix)]
fn unlink(p: &Path) -> bool {
unsafe {
return do as_c_charp(p.to_str()) |buf| {
libc::unlink(buf) == (0 as c_int)
};
}
}
}
#[cfg(unix)]
pub fn errno() -> int {
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn errno_location() -> *c_int {
#[nolink]
extern {
unsafe fn __error() -> *c_int;
}
unsafe {
__error()
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
fn errno_location() -> *c_int {
#[nolink]
extern {
unsafe fn __errno_location() -> *c_int;
}
unsafe {
__errno_location()
}
}
unsafe {
(*errno_location()) as int
}
}
#[cfg(windows)]
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
#[abi = "stdcall"]
extern "stdcall" {
unsafe fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a string representing the platform-dependent last error
pub fn last_os_error() -> ~str {
#[cfg(unix)]
fn strerror() -> ~str {
#[cfg(target_os = "macos")]
#[cfg(target_os = "android")]
#[cfg(target_os = "freebsd")]
fn strerror_r(errnum: c_int, buf: *c_char, buflen: size_t) -> c_int {
#[nolink]
extern {
unsafe fn strerror_r(errnum: c_int, buf: *c_char,
buflen: size_t) -> c_int;
}
unsafe {
strerror_r(errnum, buf, buflen)