/
os.rs
1043 lines (896 loc) · 29 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
/*!
* 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.
*/
import libc::{c_char, c_void, c_int, c_uint, size_t, ssize_t,
mode_t, pid_t, FILE};
import libc::{close, fclose};
import option::{some, none};
import getcwd = rustrt::rust_getcwd;
import consts::*;
import task::TaskBuilder;
export close, fclose, fsync_fd, waitpid;
export env, getenv, setenv, fdopen, pipe;
export getcwd, dll_filename, self_exe_path;
export exe_suffix, dll_suffix, sysname, arch, family;
export homedir, tmpdir, list_dir, list_dir_path, path_is_dir, path_exists,
make_absolute, make_dir, remove_dir, change_dir, remove_file,
copy_file;
export last_os_error;
export set_exit_status;
export walk_dir;
// FIXME: move these to str perhaps? #2620
export as_c_charp, fill_charp_buf;
extern mod rustrt {
fn rust_getcwd() -> ~str;
fn rust_path_is_dir(path: *libc::c_char) -> c_int;
fn rust_path_exists(path: *libc::c_char) -> c_int;
fn rust_list_files(path: ~str) -> ~[~str];
fn rust_process_wait(handle: c_int) -> c_int;
fn last_os_error() -> ~str;
fn rust_set_exit_status(code: libc::intptr_t);
}
const tmpbuf_sz : uint = 1000u;
fn as_c_charp<T>(s: ~str, f: fn(*c_char) -> T) -> T {
str::as_c_str(s, |b| f(b as *c_char))
}
fn fill_charp_buf(f: fn(*mut c_char, size_t) -> bool)
-> option<~str> {
let buf = vec::to_mut(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::unsafe::from_buf(b as *u8))
} else {
none
}
}
}
#[cfg(windows)]
mod win32 {
import dword = libc::types::os::arch::extra::DWORD;
fn fill_utf16_buf_and_decode(f: fn(*mut u16, dword) -> dword)
-> option<~str> {
// FIXME: remove these when export globs work properly. #1238
import libc::funcs::extra::kernel32::*;
import libc::consts::os::extra::*;
let mut n = tmpbuf_sz as dword;
let mut res = none;
let mut done = false;
while !done {
let buf = vec::to_mut(vec::from_elem(n as uint, 0u16));
do vec::as_mut_buf(buf) |b, _sz| {
let k : dword = f(b, tmpbuf_sz as dword);
if k == (0 as dword) {
done = true;
} else if (k == n &&
GetLastError() ==
ERROR_INSUFFICIENT_BUFFER as dword) {
n *= (2 as dword);
} else {
let sub = vec::slice(buf, 0u, k as uint);
res = option::some(str::from_utf16(sub));
done = true;
}
}
}
return res;
}
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_buf(t, |buf, _len| f(buf))
}
}
fn getenv(n: ~str) -> option<~str> {
global_env::getenv(n)
}
fn setenv(n: ~str, v: ~str) {
global_env::setenv(n, v)
}
fn env() -> ~[(~str,~str)] {
global_env::env()
}
mod global_env {
//! Internal module for serializing access to getenv/setenv
export getenv;
export setenv;
export env;
extern mod rustrt {
fn rust_global_env_chan_ptr() -> *libc::uintptr_t;
}
enum Msg {
MsgGetEnv(~str, comm::Chan<option<~str>>),
MsgSetEnv(~str, ~str, comm::Chan<()>),
MsgEnv(comm::Chan<~[(~str,~str)]>)
}
fn getenv(n: ~str) -> option<~str> {
let env_ch = get_global_env_chan();
let po = comm::port();
comm::send(env_ch, MsgGetEnv(n, comm::chan(po)));
comm::recv(po)
}
fn setenv(n: ~str, v: ~str) {
let env_ch = get_global_env_chan();
let po = comm::port();
comm::send(env_ch, MsgSetEnv(n, v, comm::chan(po)));
comm::recv(po)
}
fn env() -> ~[(~str,~str)] {
let env_ch = get_global_env_chan();
let po = comm::port();
comm::send(env_ch, MsgEnv(comm::chan(po)));
comm::recv(po)
}
fn get_global_env_chan() -> comm::Chan<Msg> {
let global_ptr = rustrt::rust_global_env_chan_ptr();
unsafe {
priv::chan_from_global_ptr(global_ptr, || {
// FIXME (#2621): This would be a good place to use a very
// small foreign stack
task::task().sched_mode(task::SingleThreaded).unlinked()
}, global_env_task)
}
}
fn global_env_task(msg_po: comm::Port<Msg>) {
unsafe {
do priv::weaken_task |weak_po| {
loop {
match comm::select2(msg_po, weak_po) {
either::Left(MsgGetEnv(n, resp_ch)) => {
comm::send(resp_ch, impl::getenv(n))
}
either::Left(MsgSetEnv(n, v, resp_ch)) => {
comm::send(resp_ch, impl::setenv(n, v))
}
either::Left(MsgEnv(resp_ch)) => {
comm::send(resp_ch, impl::env())
}
either::Right(_) => break
}
}
}
}
}
mod impl {
extern mod rustrt {
fn rust_env_pairs() -> ~[~str];
}
fn env() -> ~[(~str,~str)] {
let mut pairs = ~[];
for vec::each(rustrt::rust_env_pairs()) |p| {
let vs = str::splitn_char(p, '=', 1u);
assert vec::len(vs) == 2u;
vec::push(pairs, (vs[0], vs[1]));
}
return pairs;
}
#[cfg(unix)]
fn getenv(n: ~str) -> option<~str> {
unsafe {
let s = str::as_c_str(n, libc::getenv);
return if unsafe::reinterpret_cast(s) == 0 {
option::none::<~str>
} else {
let s = unsafe::reinterpret_cast(s);
option::some::<~str>(str::unsafe::from_buf(s))
};
}
}
#[cfg(windows)]
fn getenv(n: ~str) -> option<~str> {
import libc::types::os::arch::extra::*;
import libc::funcs::extra::kernel32::*;
import win32::*;
do as_utf16_p(n) |u| {
do fill_utf16_buf_and_decode() |buf, sz| {
GetEnvironmentVariableW(u, buf, sz)
}
}
}
#[cfg(unix)]
fn setenv(n: ~str, v: ~str) {
// FIXME: remove this when export globs work properly. #1238
import libc::funcs::posix01::unistd::setenv;
do str::as_c_str(n) |nbuf| {
do str::as_c_str(v) |vbuf| {
setenv(nbuf, vbuf, 1i32);
}
}
}
#[cfg(windows)]
fn setenv(n: ~str, v: ~str) {
// FIXME: remove imports when export globs work properly. #1238
import libc::funcs::extra::kernel32::*;
import win32::*;
do as_utf16_p(n) |nbuf| {
do as_utf16_p(v) |vbuf| {
SetEnvironmentVariableW(nbuf, vbuf);
}
}
}
}
}
fn fdopen(fd: c_int) -> *FILE {
return do as_c_charp(~"r") |modebuf| {
libc::fdopen(fd, modebuf)
};
}
// fsync related
#[cfg(windows)]
fn fsync_fd(fd: c_int, _level: io::fsync::Level) -> c_int {
import libc::funcs::extra::msvcrt::*;
return commit(fd);
}
#[cfg(target_os = "linux")]
fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
import 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")]
fn fsync_fd(fd: c_int, level: io::fsync::Level) -> c_int {
import libc::consts::os::extra::*;
import libc::funcs::posix88::fcntl::*;
import 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")]
fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int {
import libc::funcs::posix01::unistd::*;
return fsync(fd);
}
#[cfg(windows)]
fn waitpid(pid: pid_t) -> c_int {
return rustrt::rust_process_wait(pid);
}
#[cfg(unix)]
fn waitpid(pid: pid_t) -> c_int {
import libc::funcs::posix01::wait::*;
let status = 0 as c_int;
assert (waitpid(pid, ptr::mut_addr_of(status),
0 as c_int) != (-1 as c_int));
return status;
}
#[cfg(unix)]
fn pipe() -> {in: c_int, out: c_int} {
let fds = {mut in: 0 as c_int,
mut out: 0 as c_int };
assert (libc::pipe(ptr::mut_addr_of(fds.in)) == (0 as c_int));
return {in: fds.in, out: fds.out};
}
#[cfg(windows)]
fn pipe() -> {in: c_int, out: c_int} {
// FIXME: remove this when export globs work properly. #1238
import libc::consts::os::extra::*;
// 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 rust_run_program.
let fds = { mut in: 0 as c_int,
mut out: 0 as c_int };
let res = libc::pipe(ptr::mut_addr_of(fds.in),
1024 as c_uint,
(O_BINARY | 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 {in: fds.in, out: fds.out};
}
fn dll_filename(base: ~str) -> ~str {
return pre() + base + dll_suffix();
#[cfg(unix)]
fn pre() -> ~str { ~"lib" }
#[cfg(windows)]
fn pre() -> ~str { ~"" }
}
fn self_exe_path() -> option<Path> {
#[cfg(target_os = "freebsd")]
fn load_self() -> option<Path> {
unsafe {
import libc::funcs::bsd44::*;
import 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];
sysctl(vec::unsafe::to_ptr(mib), vec::len(mib) as c_uint,
buf as *mut c_void, ptr::mut_addr_of(sz),
ptr::null(), 0u as size_t) == (0 as c_int)
}
}
}
#[cfg(target_os = "linux")]
fn load_self() -> option<Path> {
import libc::funcs::posix01::unistd::readlink;
do fill_charp_buf() |buf, sz| {
do as_c_charp(~"/proc/self/exe") |proc_self_buf| {
readlink(proc_self_buf, buf, sz) != (-1 as ssize_t)
}
}
}
#[cfg(target_os = "macos")]
fn load_self() -> option<Path> {
// FIXME: remove imports when export globs work properly. #1238
import libc::funcs::extra::*;
do fill_charp_buf() |buf, sz| {
_NSGetExecutablePath(buf, ptr::mut_addr_of(sz as u32))
== (0 as c_int)
}
}
#[cfg(windows)]
fn load_self() -> option<Path> {
// FIXME: remove imports when export globs work properly. #1238
import libc::types::os::arch::extra::*;
import libc::funcs::extra::kernel32::*;
import win32::*;
do fill_utf16_buf_and_decode() |buf, sz| {
GetModuleFileNameW(0u as dword, buf, sz)
}
}
do option::map(load_self()) |pth| {
path::dirname(pth) + path::path_sep()
}
}
/**
* 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.
*/
fn homedir() -> option<Path> {
return match getenv(~"HOME") {
some(p) => if !str::is_empty(p) {
some(p)
} else {
secondary()
},
none => secondary()
};
#[cfg(unix)]
fn secondary() -> option<Path> {
none
}
#[cfg(windows)]
fn secondary() -> option<Path> {
do option::chain(getenv(~"USERPROFILE")) |p| {
if !str::is_empty(p) {
some(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.
*/
fn tmpdir() -> Path {
return lookup();
fn getenv_nonempty(v: Path) -> option<Path> {
match getenv(v) {
some(x) =>
if str::is_empty(x) {
none
} else {
some(x)
},
_ => none
}
}
#[cfg(unix)]
fn lookup() -> Path {
option::get_default(getenv_nonempty(~"TMPDIR"), ~"/tmp")
}
#[cfg(windows)]
fn lookup() -> Path {
option::get_default(
option::or(getenv_nonempty(~"TMP"),
option::or(getenv_nonempty(~"TEMP"),
option::or(getenv_nonempty(~"USERPROFILE"),
getenv_nonempty(~"WINDIR")))),
~"C:\\Windows")
}
}
/// Recursively walk a directory structure
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 = path::connect(p, 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
fn path_is_dir(p: Path) -> bool {
do str::as_c_str(p) |buf| {
rustrt::rust_path_is_dir(buf) != 0 as c_int
}
}
/// Indicates whether a path exists
fn path_exists(p: Path) -> bool {
do str::as_c_str(p) |buf| {
rustrt::rust_path_exists(buf) != 0 as c_int
}
}
// FIXME (#2622): under Windows, we should prepend the current drive letter
// to paths that start with a slash.
/**
* 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.
fn make_absolute(p: Path) -> Path {
if path::path_is_absolute(p) {
p
} else {
path::connect(getcwd(), p)
}
}
/// Creates a directory at the specified path
fn make_dir(p: Path, mode: c_int) -> bool {
return mkdir(p, mode);
#[cfg(windows)]
fn mkdir(p: Path, _mode: c_int) -> bool {
// FIXME: remove imports when export globs work properly. #1238
import libc::types::os::arch::extra::*;
import libc::funcs::extra::kernel32::*;
import win32::*;
// FIXME: turn mode into something useful? #2623
do as_utf16_p(p) |buf| {
CreateDirectoryW(buf, unsafe { unsafe::reinterpret_cast(0) })
!= (0 as BOOL)
}
}
#[cfg(unix)]
fn mkdir(p: Path, mode: c_int) -> bool {
do as_c_charp(p) |c| {
libc::mkdir(c, mode as mode_t) == (0 as c_int)
}
}
}
/// Lists the contents of a directory
fn list_dir(p: Path) -> ~[~str] {
#[cfg(unix)]
fn star(p: ~str) -> ~str { p }
#[cfg(windows)]
fn star(p: ~str) -> ~str {
let pl = str::len(p);
if pl == 0u || (p[pl - 1u] as char != path::consts::path_sep
|| p[pl - 1u] as char != path::consts::alt_path_sep) {
p + path::path_sep() + ~"*"
} else {
p + ~"*"
}
}
do rustrt::rust_list_files(star(p)).filter |filename| {
filename != ~"." && filename != ~".."
}
}
/**
* Lists the contents of a directory
*
* This version prepends each entry with the directory.
*/
fn list_dir_path(p: Path) -> ~[~str] {
let mut p = p;
let pl = str::len(p);
if pl == 0u || (p[pl - 1u] as char != path::consts::path_sep
&& p[pl - 1u] as char != path::consts::alt_path_sep) {
p += path::path_sep();
}
os::list_dir(p).map(|f| p + f)
}
/// Removes a directory at the specified path
fn remove_dir(p: Path) -> bool {
return rmdir(p);
#[cfg(windows)]
fn rmdir(p: Path) -> bool {
// FIXME: remove imports when export globs work properly. #1238
import libc::funcs::extra::kernel32::*;
import libc::types::os::arch::extra::*;
import win32::*;
return do as_utf16_p(p) |buf| {
RemoveDirectoryW(buf) != (0 as BOOL)
};
}
#[cfg(unix)]
fn rmdir(p: Path) -> bool {
return do as_c_charp(p) |buf| {
libc::rmdir(buf) == (0 as c_int)
};
}
}
fn change_dir(p: Path) -> bool {
return chdir(p);
#[cfg(windows)]
fn chdir(p: Path) -> bool {
// FIXME: remove imports when export globs work properly. #1238
import libc::funcs::extra::kernel32::*;
import libc::types::os::arch::extra::*;
import win32::*;
return do as_utf16_p(p) |buf| {
SetCurrentDirectoryW(buf) != (0 as BOOL)
};
}
#[cfg(unix)]
fn chdir(p: Path) -> bool {
return do as_c_charp(p) |buf| {
libc::chdir(buf) == (0 as c_int)
};
}
}
/// Copies a file from one location to another
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 {
// FIXME: remove imports when export globs work properly. #1238
import libc::funcs::extra::kernel32::*;
import libc::types::os::arch::extra::*;
import win32::*;
return do as_utf16_p(from) |fromp| {
do as_utf16_p(to) |top| {
CopyFileW(fromp, top, (0 as BOOL)) != (0 as BOOL)
}
}
}
#[cfg(unix)]
fn do_copy_file(from: Path, to: Path) -> bool {
let istream = do as_c_charp(from) |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) |top| {
do as_c_charp(~"w+b") |modebuf| {
libc::fopen(top, modebuf)
}
};
if ostream as uint == 0u {
fclose(istream);
return false;
}
let mut buf : ~[mut u8] = ~[mut];
let bufsize = 8192u;
vec::reserve(buf, 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
fn remove_file(p: Path) -> bool {
return unlink(p);
#[cfg(windows)]
fn unlink(p: Path) -> bool {
// FIXME (similar to Issue #2006): remove imports when export globs
// work properly.
import libc::funcs::extra::kernel32::*;
import libc::types::os::arch::extra::*;
import win32::*;
return do as_utf16_p(p) |buf| {
DeleteFileW(buf) != (0 as BOOL)
};
}
#[cfg(unix)]
fn unlink(p: Path) -> bool {
return do as_c_charp(p) |buf| {
libc::unlink(buf) == (0 as c_int)
};
}
}
/// Get a string representing the platform-dependent last error
fn last_os_error() -> ~str {
rustrt::last_os_error()
}
/**
* Sets the process exit code
*
* Sets the exit code returned by the process if all supervised tasks
* terminate successfully (without failing). If the current root task fails
* and is supervised by the scheduler then any user-specified exit status is
* ignored and the process exits with the default failure status
*/
fn set_exit_status(code: int) {
rustrt::rust_set_exit_status(code as libc::intptr_t);
}
#[cfg(unix)]
fn family() -> ~str { ~"unix" }
#[cfg(windows)]
fn family() -> ~str { ~"windows" }
#[cfg(target_os = "macos")]
mod consts {
fn sysname() -> ~str { ~"macos" }
fn exe_suffix() -> ~str { ~"" }
fn dll_suffix() -> ~str { ~".dylib" }
}
#[cfg(target_os = "freebsd")]
mod consts {
fn sysname() -> ~str { ~"freebsd" }
fn exe_suffix() -> ~str { ~"" }
fn dll_suffix() -> ~str { ~".so" }
}
#[cfg(target_os = "linux")]
mod consts {
fn sysname() -> ~str { ~"linux" }
fn exe_suffix() -> ~str { ~"" }
fn dll_suffix() -> ~str { ~".so" }
}
#[cfg(target_os = "win32")]
mod consts {
fn sysname() -> ~str { ~"win32" }
fn exe_suffix() -> ~str { ~".exe" }
fn dll_suffix() -> ~str { ~".dll" }
}
#[cfg(target_arch = "x86")]
fn arch() -> ~str { ~"x86" }
#[cfg(target_arch = "x86_64")]
fn arch() -> ~str { ~"x86_64" }
#[cfg(target_arch = "arm")]
fn arch() -> str { ~"arm" }
#[cfg(test)]
mod tests {
#[test]
fn last_os_error() {
log(debug, last_os_error());
}
fn make_rand_name() -> ~str {
import rand;
let rng: rand::Rng = rand::rng();
let n = ~"TEST" + rng.gen_str(10u);
assert option::is_none(getenv(n));
n
}
#[test]
fn test_setenv() {
let n = make_rand_name();
setenv(n, ~"VALUE");
assert getenv(n) == option::some(~"VALUE");
}
#[test]
#[ignore(cfg(windows))]
#[ignore]
fn test_setenv_overwrite() {
let n = make_rand_name();
setenv(n, ~"1");
setenv(n, ~"2");
assert getenv(n) == option::some(~"2");
setenv(n, ~"");
assert getenv(n) == option::some(~"");
}
// Windows GetEnvironmentVariable requires some extra work to make sure
// the buffer the variable is copied into is the right size
#[test]
#[ignore(cfg(windows))]
#[ignore]
fn test_getenv_big() {
let mut s = ~"";
let mut i = 0;
while i < 100 { s += ~"aaaaaaaaaa"; i += 1; }
let n = make_rand_name();
setenv(n, s);
log(debug, s);
assert getenv(n) == option::some(s);
}
#[test]
fn test_self_exe_path() {
let path = os::self_exe_path();
assert option::is_some(path);
let path = option::get(path);
log(debug, path);
// Hard to test this function
if os::sysname() != ~"win32" {
assert str::starts_with(path, path::path_sep());
} else {
assert path[1] == ':' as u8;
}
}
#[test]
#[ignore]
fn test_env_getenv() {
let e = env();
assert vec::len(e) > 0u;
for vec::each(e) |p| {
let (n, v) = p;
log(debug, n);
let v2 = getenv(n);
// MingW seems to set some funky environment variables like
// "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
// from env() but not visible from getenv().
assert option::is_none(v2) || v2 == option::some(v);
}
}
#[test]
fn test_env_setenv() {
let n = make_rand_name();
let mut e = env();
setenv(n, ~"VALUE");
assert !vec::contains(e, (n, ~"VALUE"));
e = env();
assert vec::contains(e, (n, ~"VALUE"));
}
#[test]
fn test() {
assert (!path::path_is_absolute(~"test-path"));
log(debug, ~"Current working directory: " + getcwd());
log(debug, make_absolute(~"test-path"));
log(debug, make_absolute(~"/usr/bin"));
}
#[test]
#[cfg(unix)]
fn homedir() {
let oldhome = getenv(~"HOME");
setenv(~"HOME", ~"/home/MountainView");
assert os::homedir() == some(~"/home/MountainView");
setenv(~"HOME", ~"");
assert os::homedir() == none;
option::iter(oldhome, |s| setenv(~"HOME", s));
}
#[test]
#[cfg(windows)]
fn homedir() {
let oldhome = getenv(~"HOME");
let olduserprofile = getenv(~"USERPROFILE");
setenv(~"HOME", ~"");
setenv(~"USERPROFILE", ~"");
assert os::homedir() == none;
setenv(~"HOME", ~"/home/MountainView");
assert os::homedir() == some(~"/home/MountainView");
setenv(~"HOME", ~"");
setenv(~"USERPROFILE", ~"/home/MountainView");
assert os::homedir() == some(~"/home/MountainView");
setenv(~"USERPROFILE", ~"/home/MountainView");
assert os::homedir() == some(~"/home/MountainView");
setenv(~"HOME", ~"/home/MountainView");
setenv(~"USERPROFILE", ~"/home/PaloAlto");
assert os::homedir() == some(~"/home/MountainView");
option::iter(oldhome, |s| setenv(~"HOME", s));
option::iter(olduserprofile,
|s| setenv(~"USERPROFILE", s));
}
#[test]
fn tmpdir() {
assert !str::is_empty(os::tmpdir());
}
// Issue #712
#[test]
fn test_list_dir_no_invalid_memory_access() { os::list_dir(~"."); }
#[test]
fn list_dir() {
let dirs = os::list_dir(~".");
// Just assuming that we've got some contents in the current directory
assert (vec::len(dirs) > 0u);
for vec::each(dirs) |dir| { log(debug, dir); }
}
#[test]
fn path_is_dir() {
assert (os::path_is_dir(~"."));
assert (!os::path_is_dir(~"test/stdtest/fs.rs"));
}
#[test]
fn path_exists() {
assert (os::path_exists(~"."));