/
os.rs
1558 lines (1380 loc) · 46.4 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.
*/
#[allow(missing_doc)];
#[cfg(target_os = "macos")]
#[cfg(windows)]
use iter::range;
use clone::Clone;
use container::Container;
use libc;
use libc::{c_char, c_void, c_int};
use option::{Some, None, Option};
use os;
use ops::Drop;
use result::{Err, Ok, Result};
use ptr;
use str;
use str::{Str, StrSlice};
use fmt;
use unstable::finally::Finally;
use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
use path::{Path, GenericPath};
use iter::Iterator;
use vec::{Vector, CloneableVector, ImmutableVector, MutableVector, OwnedVector};
use ptr::RawPtr;
#[cfg(unix)]
use c_str::ToCStr;
/// Delegates to the libc close() function, returning the same return value.
pub fn close(fd: int) -> int {
unsafe {
libc::close(fd as c_int) as int
}
}
pub static TMPBUF_SZ : uint = 1000u;
static BUF_BYTES : uint = 2048u;
#[cfg(unix)]
pub fn getcwd() -> Path {
use c_str::CString;
let mut buf = [0 as c_char, ..BUF_BYTES];
unsafe {
if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
fail!()
}
Path::new(CString::new(buf.as_ptr(), false))
}
}
#[cfg(windows)]
pub fn getcwd() -> Path {
use libc::DWORD;
use libc::GetCurrentDirectoryW;
let mut buf = [0 as u16, ..BUF_BYTES];
unsafe {
if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
fail!();
}
}
Path::new(str::from_utf16(buf))
}
#[cfg(windows)]
pub mod win32 {
use libc::types::os::arch::extra::DWORD;
use libc;
use option::{None, Option};
use option;
use os::TMPBUF_SZ;
use str::StrSlice;
use str;
use vec::{MutableVector, ImmutableVector, OwnedVector};
use vec;
pub fn fill_utf16_buf_and_decode(f: |*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 buf = vec::from_elem(n as uint, 0u16);
let k = f(buf.as_mut_ptr(), 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 = buf.slice(0, k as uint);
res = option::Some(str::from_utf16(sub));
}
}
return res;
}
}
pub fn as_utf16_p<T>(s: &str, f: |*u16| -> T) -> T {
let mut t = s.to_utf16();
// Null terminate before passing on.
t.push(0u16);
f(t.as_ptr())
}
}
/*
Accessing environment variables is not generally threadsafe.
Serialize access through a global lock.
*/
fn with_env_lock<T>(f: || -> T) -> T {
use unstable::mutex::{Mutex, MUTEX_INIT};
use unstable::finally::Finally;
static mut lock: Mutex = MUTEX_INIT;
unsafe {
return (|| {
lock.lock();
f()
}).finally(|| lock.unlock());
}
}
/// Returns a vector of (variable, value) pairs for all the environment
/// variables of the current process.
pub fn env() -> ~[(~str,~str)] {
unsafe {
#[cfg(windows)]
unsafe fn get_env_pairs() -> ~[~str] {
use c_str;
use str::StrSlice;
use libc::funcs::extra::kernel32::{
GetEnvironmentStringsA,
FreeEnvironmentStringsA
};
let ch = GetEnvironmentStringsA();
if ch as uint == 0 {
fail!("os::env() failure getting env string from OS: {}",
os::last_os_error());
}
let mut result = ~[];
c_str::from_c_multistring(ch as *c_char, None, |cstr| {
result.push(cstr.as_str().unwrap().to_owned());
});
FreeEnvironmentStringsA(ch);
result
}
#[cfg(unix)]
unsafe fn get_env_pairs() -> ~[~str] {
extern {
fn rust_env_pairs() -> **c_char;
}
let environ = rust_env_pairs();
if environ as uint == 0 {
fail!("os::env() failure getting env string from OS: {}",
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: {}", env_pair);
result.push(env_pair);
});
result
}
fn env_convert(input: ~[~str]) -> ~[(~str, ~str)] {
let mut pairs = ~[];
for p in input.iter() {
let vs: ~[&str] = p.splitn('=', 1).collect();
debug!("splitting: len: {}", vs.len());
assert_eq!(vs.len(), 2);
pairs.push((vs[0].to_owned(), vs[1].to_owned()));
}
pairs
}
with_env_lock(|| {
let unparsed_environ = get_env_pairs();
env_convert(unparsed_environ)
})
}
}
#[cfg(unix)]
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
pub fn getenv(n: &str) -> Option<~str> {
unsafe {
with_env_lock(|| {
let s = n.with_c_str(|buf| libc::getenv(buf));
if s.is_null() {
None
} else {
Some(str::raw::from_c_str(s))
}
})
}
}
#[cfg(windows)]
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
pub fn getenv(n: &str) -> Option<~str> {
unsafe {
with_env_lock(|| {
use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
as_utf16_p(n, |u| {
fill_utf16_buf_and_decode(|buf, sz| {
libc::GetEnvironmentVariableW(u, buf, sz)
})
})
})
}
}
#[cfg(unix)]
/// Sets the environment variable `n` to the value `v` for the currently running
/// process
pub fn setenv(n: &str, v: &str) {
unsafe {
with_env_lock(|| {
n.with_c_str(|nbuf| {
v.with_c_str(|vbuf| {
libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
})
})
})
}
}
#[cfg(windows)]
/// Sets the environment variable `n` to the value `v` for the currently running
/// process
pub fn setenv(n: &str, v: &str) {
unsafe {
with_env_lock(|| {
use os::win32::as_utf16_p;
as_utf16_p(n, |nbuf| {
as_utf16_p(v, |vbuf| {
libc::SetEnvironmentVariableW(nbuf, vbuf);
})
})
})
}
}
/// Remove a variable from the environment entirely
pub fn unsetenv(n: &str) {
#[cfg(unix)]
fn _unsetenv(n: &str) {
unsafe {
with_env_lock(|| {
n.with_c_str(|nbuf| {
libc::funcs::posix01::unistd::unsetenv(nbuf);
})
})
}
}
#[cfg(windows)]
fn _unsetenv(n: &str) {
unsafe {
with_env_lock(|| {
use os::win32::as_utf16_p;
as_utf16_p(n, |nbuf| {
libc::SetEnvironmentVariableW(nbuf, ptr::null());
})
})
}
}
_unsetenv(n);
}
pub struct Pipe {
input: c_int,
out: c_int
}
#[cfg(unix)]
pub fn pipe() -> Pipe {
unsafe {
let mut fds = Pipe {input: 0,
out: 0};
assert_eq!(libc::pipe(&mut fds.input), 0);
return Pipe {input: fds.input, 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 std::run.
let mut fds = Pipe {input: 0,
out: 0};
let res = libc::pipe(&mut fds.input, 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int);
assert_eq!(res, 0);
assert!((fds.input != -1 && fds.input != 0 ));
assert!((fds.out != -1 && fds.input != 0));
return Pipe {input: fds.input, out: fds.out};
}
}
/// Returns the proper dll filename for the given basename of a file.
pub fn dll_filename(base: &str) -> ~str {
format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
}
/// Optionally returns the filesystem path of the current executable which is
/// running. If any failure occurs, None is returned.
pub fn self_exe_name() -> Option<Path> {
#[cfg(target_os = "freebsd")]
fn load_self() -> Option<~[u8]> {
unsafe {
use libc::funcs::bsd44::*;
use libc::consts::os::extra::*;
use vec;
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: libc::size_t = 0;
let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
ptr::mut_null(), &mut sz, ptr::null(),
0u as libc::size_t);
if err != 0 { return None; }
if sz == 0 { return None; }
let mut v: ~[u8] = vec::with_capacity(sz as uint);
let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint,
v.as_mut_ptr() as *mut c_void, &mut sz, ptr::null(),
0u as libc::size_t);
if err != 0 { return None; }
if sz == 0 { return None; }
v.set_len(sz as uint - 1); // chop off trailing NUL
Some(v)
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
fn load_self() -> Option<~[u8]> {
use std::io;
match io::fs::readlink(&Path::new("/proc/self/exe")) {
Ok(path) => Some(path.as_vec().to_owned()),
Err(..) => None
}
}
#[cfg(target_os = "macos")]
fn load_self() -> Option<~[u8]> {
unsafe {
use libc::funcs::extra::_NSGetExecutablePath;
use vec;
let mut sz: u32 = 0;
_NSGetExecutablePath(ptr::mut_null(), &mut sz);
if sz == 0 { return None; }
let mut v: ~[u8] = vec::with_capacity(sz as uint);
let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
if err != 0 { return None; }
v.set_len(sz as uint - 1); // chop off trailing NUL
Some(v)
}
}
#[cfg(windows)]
fn load_self() -> Option<~[u8]> {
use str::OwnedStr;
unsafe {
use os::win32::fill_utf16_buf_and_decode;
fill_utf16_buf_and_decode(|buf, sz| {
libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
}).map(|s| s.into_bytes())
}
}
load_self().and_then(Path::new_opt)
}
/// Optionally returns the filesystem path to the current executable which is
/// running. Like self_exe_name() but without the binary's name.
/// If any failure occurs, None is returned.
pub fn self_exe_path() -> Option<Path> {
self_exe_name().map(|mut p| { p.pop(); p })
}
/**
* 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> {
// FIXME (#7188): getenv needs a ~[u8] variant
return match getenv("HOME") {
Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()),
_ => secondary()
};
#[cfg(unix)]
fn secondary() -> Option<Path> {
None
}
#[cfg(windows)]
fn secondary() -> Option<Path> {
getenv("USERPROFILE").and_then(|p| {
if !p.is_empty() {
Path::new_opt(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 Android, there is no global temporary folder (it is usually allocated
* per-app), hence returns '/data/tmp' which is commonly used.
*
* 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 x.is_empty() {
None
} else {
Path::new_opt(x)
},
_ => None
}
}
#[cfg(unix)]
fn lookup() -> Path {
if cfg!(target_os = "android") {
Path::new("/data/tmp")
} else {
getenv_nonempty("TMPDIR").unwrap_or(Path::new("/tmp"))
}
}
#[cfg(windows)]
fn lookup() -> Path {
getenv_nonempty("TMP").or(
getenv_nonempty("TEMP").or(
getenv_nonempty("USERPROFILE").or(
getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
}
}
/**
* 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() {
p.clone()
} else {
let mut ret = getcwd();
ret.push(p);
ret
}
}
/// Changes the current working directory to the specified path, returning
/// whether the change was completed successfully or not.
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 as_utf16_p(p.as_str().unwrap(), |buf| {
libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
});
}
}
#[cfg(unix)]
fn chdir(p: &Path) -> bool {
p.with_c_str(|buf| {
unsafe {
libc::chdir(buf) == (0 as c_int)
}
})
}
}
#[cfg(unix)]
/// Returns the platform-specific value of errno
pub fn errno() -> int {
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn errno_location() -> *c_int {
#[nolink]
extern {
fn __error() -> *c_int;
}
unsafe {
__error()
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
fn errno_location() -> *c_int {
#[nolink]
extern {
fn __errno_location() -> *c_int;
}
unsafe {
__errno_location()
}
}
unsafe {
(*errno_location()) as int
}
}
#[cfg(windows)]
/// Returns the platform-specific value of errno
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
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: *mut c_char, buflen: libc::size_t)
-> c_int {
#[nolink]
extern {
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int;
}
unsafe {
strerror_r(errnum, buf, buflen)
}
}
// GNU libc provides a non-compliant version of strerror_r by default
// and requires macros to instead use the POSIX compliant variant.
// So we just use __xpg_strerror_r which is always POSIX compliant
#[cfg(target_os = "linux")]
fn strerror_r(errnum: c_int, buf: *mut c_char,
buflen: libc::size_t) -> c_int {
#[nolink]
extern {
fn __xpg_strerror_r(errnum: c_int,
buf: *mut c_char,
buflen: libc::size_t)
-> c_int;
}
unsafe {
__xpg_strerror_r(errnum, buf, buflen)
}
}
let mut buf = [0 as c_char, ..TMPBUF_SZ];
let p = buf.as_mut_ptr();
unsafe {
if strerror_r(errno() as c_int, p, buf.len() as libc::size_t) < 0 {
fail!("strerror_r failure");
}
str::raw::from_c_str(p as *c_char)
}
}
#[cfg(windows)]
fn strerror() -> ~str {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
use libc::types::os::arch::extra::WCHAR;
#[link_name = "kernel32"]
extern "system" {
fn FormatMessageW(flags: DWORD,
lpSrc: LPVOID,
msgId: DWORD,
langId: DWORD,
buf: LPWSTR,
nsize: DWORD,
args: *c_void)
-> DWORD;
}
static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as DWORD;
let err = errno() as DWORD;
let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
unsafe {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::mut_null(),
err,
langId,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null());
if res == 0 {
fail!("[{}] FormatMessage failure", errno());
}
str::from_utf16(buf)
}
}
strerror()
}
static mut EXIT_STATUS: AtomicInt = INIT_ATOMIC_INT;
/**
* 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.
*
* Note that this is not synchronized against modifications of other threads.
*/
pub fn set_exit_status(code: int) {
unsafe { EXIT_STATUS.store(code, SeqCst) }
}
/// Fetches the process's current exit code. This defaults to 0 and can change
/// by calling `set_exit_status`.
pub fn get_exit_status() -> int {
unsafe { EXIT_STATUS.load(SeqCst) }
}
#[cfg(target_os = "macos")]
unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~str] {
let mut args = ~[];
for i in range(0u, argc as uint) {
args.push(str::raw::from_c_str(*argv.offset(i as int)));
}
args
}
/**
* Returns the command line arguments
*
* Returns a list of the command line arguments.
*/
#[cfg(target_os = "macos")]
fn real_args() -> ~[~str] {
unsafe {
let (argc, argv) = (*_NSGetArgc() as int,
*_NSGetArgv() as **c_char);
load_argc_and_argv(argc, argv)
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[cfg(target_os = "freebsd")]
fn real_args() -> ~[~str] {
use rt;
match rt::args::clone() {
Some(args) => args,
None => fail!("process arguments not initialized")
}
}
#[cfg(windows)]
fn real_args() -> ~[~str] {
use vec;
let mut nArgs: c_int = 0;
let lpArgCount: *mut c_int = &mut nArgs;
let lpCmdLine = unsafe { GetCommandLineW() };
let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
let mut args = ~[];
for i in range(0u, nArgs as uint) {
unsafe {
// Determine the length of this argument.
let ptr = *szArgList.offset(i as int);
let mut len = 0;
while *ptr.offset(len as int) != 0 { len += 1; }
// Push it onto the list.
args.push(vec::raw::buf_as_slice(ptr, len,
str::from_utf16));
}
}
unsafe {
LocalFree(szArgList as *c_void);
}
return args;
}
type LPCWSTR = *u16;
#[cfg(windows)]
#[link_name="kernel32"]
extern "system" {
fn GetCommandLineW() -> LPCWSTR;
fn LocalFree(ptr: *c_void);
}
#[cfg(windows)]
#[link_name="shell32"]
extern "system" {
fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16;
}
/// Returns the arguments which this program was started with (normally passed
/// via the command line).
pub fn args() -> ~[~str] {
real_args()
}
#[cfg(target_os = "macos")]
extern {
// These functions are in crt_externs.h.
pub fn _NSGetArgc() -> *c_int;
pub fn _NSGetArgv() -> ***c_char;
}
// Round up `from` to be divisible by `to`
fn round_up(from: uint, to: uint) -> uint {
let r = if from % to == 0 {
from
} else {
from + to - (from % to)
};
if r == 0 {
to
} else {
r
}
}
#[cfg(unix)]
pub fn page_size() -> uint {
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as uint
}
}
#[cfg(windows)]
pub fn page_size() -> uint {
unsafe {
let mut info = libc::SYSTEM_INFO::new();
libc::GetSystemInfo(&mut info);
return info.dwPageSize as uint;
}
}
/// A memory mapped file or chunk of memory. This is a very system-specific
/// interface to the OS's memory mapping facilities (`mmap` on POSIX,
/// `VirtualAlloc`/`CreateFileMapping` on win32). It makes no attempt at
/// abstracting platform differences, besides in error values returned. Consider
/// yourself warned.
///
/// The memory map is released (unmapped) when the destructor is run, so don't
/// let it leave scope by accident if you want it to stick around.
pub struct MemoryMap {
/// Pointer to the memory created or modified by this map.
data: *mut u8,
/// Number of bytes this map applies to
len: uint,
/// Type of mapping
kind: MemoryMapKind
}
/// Type of memory map
pub enum MemoryMapKind {
/// Virtual memory map. Usually used to change the permissions of a given
/// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
MapFile(*u8),
/// Virtual memory map. Usually used to change the permissions of a given
/// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
/// Windows.
MapVirtual
}
/// Options the memory map is created with
pub enum MapOption {
/// The memory should be readable
MapReadable,
/// The memory should be writable
MapWritable,
/// The memory should be executable
MapExecutable,
/// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
/// POSIX.
MapAddr(*u8),
/// Create a memory mapping for a file with a given fd.
MapFd(c_int),
/// When using `MapFd`, the start of the map is `uint` bytes from the start
/// of the file.
MapOffset(uint),
/// On POSIX, this can be used to specify the default flags passed to
/// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
/// `MAP_ANON`. This will override both of those. This is platform-specific
/// (the exact values used) and ignored on Windows.
MapNonStandardFlags(c_int),
}
/// Possible errors when creating a map.
pub enum MapError {
/// ## The following are POSIX-specific
///
/// fd was not open for reading or, if using `MapWritable`, was not open for
/// writing.
ErrFdNotAvail,
/// fd was not valid
ErrInvalidFd,
/// Either the address given by `MapAddr` or offset given by `MapOffset` was
/// not a multiple of `MemoryMap::granularity` (unaligned to page size).
ErrUnaligned,
/// With `MapFd`, the fd does not support mapping.
ErrNoMapSupport,
/// If using `MapAddr`, the address + `min_len` was outside of the process's
/// address space. If using `MapFd`, the target of the fd didn't have enough
/// resources to fulfill the request.
ErrNoMem,
/// A zero-length map was requested. This is invalid according to
/// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
/// Not all platforms obey this, but this wrapper does.
ErrZeroLength,
/// Unrecognized error. The inner value is the unrecognized errno.
ErrUnknown(int),
/// ## The following are win32-specific
///
/// Unsupported combination of protection flags
/// (`MapReadable`/`MapWritable`/`MapExecutable`).
ErrUnsupProt,
/// When using `MapFd`, `MapOffset` was given (Windows does not support this
/// at all)
ErrUnsupOffset,
/// When using `MapFd`, there was already a mapping to the file.
ErrAlreadyExists,
/// Unrecognized error from `VirtualAlloc`. The inner value is the return
/// value of GetLastError.
ErrVirtualAlloc(uint),
/// Unrecognized error from `CreateFileMapping`. The inner value is the
/// return value of `GetLastError`.
ErrCreateFileMappingW(uint),
/// Unrecognized error from `MapViewOfFile`. The inner value is the return
/// value of `GetLastError`.
ErrMapViewOfFile(uint)
}
impl fmt::Show for MapError {
fn fmt(val: &MapError, out: &mut fmt::Formatter) -> fmt::Result {
let str = match *val {
ErrFdNotAvail => "fd not available for reading or writing",
ErrInvalidFd => "Invalid fd",
ErrUnaligned => {
"Unaligned address, invalid flags, negative length or \
unaligned offset"
}
ErrNoMapSupport=> "File doesn't support mapping",
ErrNoMem => "Invalid address, or not enough available memory",
ErrUnsupProt => "Protection mode unsupported",
ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
ErrAlreadyExists => "File mapping for specified file already exists",
ErrZeroLength => "Zero-length mapping not allowed",
ErrUnknown(code) => {
return write!(out.buf, "Unknown error = {}", code)
},
ErrVirtualAlloc(code) => {
return write!(out.buf, "VirtualAlloc failure = {}", code)
},
ErrCreateFileMappingW(code) => {
return write!(out.buf, "CreateFileMappingW failure = {}", code)
},
ErrMapViewOfFile(code) => {
return write!(out.buf, "MapViewOfFile failure = {}", code)
}
};
write!(out.buf, "{}", str)
}
}
#[cfg(unix)]
impl MemoryMap {
/// Create a new mapping with the given `options`, at least `min_len` bytes
/// long. `min_len` must be greater than zero; see the note on
/// `ErrZeroLength`.
pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
use libc::off_t;
use cmp::Equiv;
if min_len == 0 {
return Err(ErrZeroLength)
}
let mut addr: *u8 = ptr::null();
let mut prot = 0;
let mut flags = libc::MAP_PRIVATE;
let mut fd = -1;
let mut offset = 0;
let mut custom_flags = false;
let len = round_up(min_len, page_size());
for &o in options.iter() {
match o {
MapReadable => { prot |= libc::PROT_READ; },
MapWritable => { prot |= libc::PROT_WRITE; },
MapExecutable => { prot |= libc::PROT_EXEC; },