Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
purestd/src/env.rs at master · KarpelesLab/purestd · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
See all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
KarpelesLab
purestd
Repository navigation
Code
Issues
Pull requests
1
(1)
Actions
Projects
Security and quality
Insights
More
items
Files
Expand file tree
master
Breadcrumbs
purestd
/
src
/
env.rs
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
215 lines (190 loc) · 7.01 KB
master
Breadcrumbs
purestd
/
src
/
env.rs
Copy path
Top
File metadata and controls
Code
Blame
215 lines (190 loc) · 7.01 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
//! Process arguments and environment — the `std::env` subset, read from the
//! values the loader hands to `_start`.
//!
//! `argv`/`envp` are the classic C `char**` arrays (NUL-terminated C strings,
//! the arrays themselves NULL-terminated). We capture the pointers once at
//! startup and decode lazily, lossily as UTF-8 (matching how `std` treats
//! non-Unicode on a best-effort basis here).
use
crate
::
alloc
::
string
::
String
;
use
core
::
ffi
::
{
c_char
,
CStr
}
;
use
core
::
fmt
;
use
core
::
ptr
;
use
core
::
sync
::
atomic
::
{
AtomicPtr
,
AtomicUsize
,
Ordering
}
;
static
ARGC
:
AtomicUsize
=
AtomicUsize
::
new
(
0
)
;
static
ARGV
:
AtomicPtr
<
*
const
u8
>
=
AtomicPtr
::
new
(
ptr
::
null_mut
(
)
)
;
static
ENVP
:
AtomicPtr
<
*
const
u8
>
=
AtomicPtr
::
new
(
ptr
::
null_mut
(
)
)
;
/// Record the loader-provided argument and environment vectors. Called once by
/// the [`entry!`](crate::entry) glue before user `main`.
pub
(
crate
)
unsafe
fn
init
(
argc
:
usize
,
argv
:
*
const
*
const
u8
,
envp
:
*
const
*
const
u8
)
{
ARGC
.
store
(
argc
,
Ordering
::
Relaxed
)
;
ARGV
.
store
(
argv
as
*
mut
*
const
u8
,
Ordering
::
Relaxed
)
;
ENVP
.
store
(
envp
as
*
mut
*
const
u8
,
Ordering
::
Relaxed
)
;
}
/// WASI startup: `argv` is supplied by the command crt; the environment is
/// fetched via WASI `environ_get` into leaked buffers (process-lifetime).
#
[
cfg
(
target_family =
"wasm"
)
]
pub
(
crate
)
unsafe
fn
init_wasm
(
argc
:
usize
,
argv
:
*
const
*
const
u8
)
{
use
crate
::
alloc
::
vec
::
Vec
;
use
crate
::
arch
::
wasi
;
ARGC
.
store
(
argc
,
Ordering
::
Relaxed
)
;
ARGV
.
store
(
argv
as
*
mut
*
const
u8
,
Ordering
::
Relaxed
)
;
let
mut
count
:
usize
=
0
;
let
mut
buf_size
:
usize
=
0
;
if
wasi
::
environ_sizes_get
(
&
mut
count
,
&
mut
buf_size
)
==
0
&& count >
0
{
let
mut
ptrs
:
Vec
<
*
mut
u8
>
=
Vec
::
with_capacity
(
count +
1
)
;
ptrs
.
resize
(
count +
1
,
ptr
::
null_mut
(
)
)
;
let
mut
buf
:
Vec
<
u8
>
=
Vec
::
with_capacity
(
buf_size
.
max
(
1
)
)
;
buf
.
resize
(
buf_size
.
max
(
1
)
,
0
)
;
if
wasi
::
environ_get
(
ptrs
.
as_mut_ptr
(
)
,
buf
.
as_mut_ptr
(
)
)
==
0
{
ptrs
[
count
]
= ptr
::
null_mut
(
)
;
// NULL-terminate the char** array
let
leaked = ptrs
.
leak
(
)
;
core
::
mem
::
forget
(
buf
)
;
// the strings the pointers reference
ENVP
.
store
(
leaked
.
as_mut_ptr
(
)
as
*
mut
*
const
u8
,
Ordering
::
Relaxed
)
;
}
}
}
#
[
inline
]
unsafe
fn
cstr_to_string
(
p
:
*
const
u8
)
->
String
{
let
bytes =
CStr
::
from_ptr
(
p
as
*
const
c_char
)
.
to_bytes
(
)
;
String
::
from_utf8_lossy
(
bytes
)
.
into_owned
(
)
}
/// Iterator over the program's command-line arguments. `args().next()` is the
/// program path, mirroring `std::env::args()`.
pub
struct
Args
{
idx
:
usize
,
argc
:
usize
,
argv
:
*
const
*
const
u8
,
}
impl
Iterator
for
Args
{
type
Item
=
String
;
fn
next
(
&
mut
self
)
->
Option
<
String
>
{
if
self
.
idx
>=
self
.
argc
||
self
.
argv
.
is_null
(
)
{
return
None
;
}
let
p =
unsafe
{
*
self
.
argv
.
add
(
self
.
idx
)
}
;
self
.
idx
+=
1
;
if
p
.
is_null
(
)
{
return
None
;
}
Some
(
unsafe
{
cstr_to_string
(
p
)
}
)
}
}
impl
ExactSizeIterator
for
Args
{
fn
len
(
&
self
)
->
usize
{
self
.
argc
.
saturating_sub
(
self
.
idx
)
}
}
/// Returns the command-line arguments, the first being the program path.
pub
fn
args
(
)
->
Args
{
Args
{
idx
:
0
,
argc
:
ARGC
.
load
(
Ordering
::
Relaxed
)
,
argv
:
ARGV
.
load
(
Ordering
::
Relaxed
)
as
*
const
*
const
u8
,
}
}
// The mutable environment: lazily seeded from the loader's `envp`, then owned by
// us so `set_var`/`remove_var` work (std keeps its own copy of `environ` too).
use
crate
::
collections
::
BTreeMap
;
use
crate
::
sync
::
{
Mutex
,
OnceLock
}
;
static
ENV_MAP
:
OnceLock
<
Mutex
<
BTreeMap
<
String
,
String
>
>
>
=
OnceLock
::
new
(
)
;
fn
env_map
(
)
->
&
'
static
Mutex
<
BTreeMap
<
String
,
String
>
>
{
ENV_MAP
.
get_or_init
(
||
{
let
mut
m =
BTreeMap
::
new
(
)
;
let
envp =
ENVP
.
load
(
Ordering
::
Relaxed
)
as
*
const
*
const
u8
;
if
!envp
.
is_null
(
)
{
let
mut
i =
0
;
loop
{
let
p =
unsafe
{
*
envp
.
add
(
i
)
}
;
if
p
.
is_null
(
)
{
break
;
}
i +=
1
;
let
bytes =
unsafe
{
CStr
::
from_ptr
(
p
as
*
const
c_char
)
.
to_bytes
(
)
}
;
if
let
Some
(
eq
)
= bytes
.
iter
(
)
.
position
(
|
&
b| b ==
b'='
)
{
let
k =
String
::
from_utf8_lossy
(
&
bytes
[
..eq
]
)
.
into_owned
(
)
;
let
v =
String
::
from_utf8_lossy
(
&
bytes
[
eq +
1
..
]
)
.
into_owned
(
)
;
m
.
insert
(
k
,
v
)
;
}
}
}
Mutex
::
new
(
m
)
}
)
}
/// Iterator over `(key, value)` environment pairs.
pub
struct
Vars
{
inner
:
crate
::
alloc
::
vec
::
IntoIter
<
(
String
,
String
)
>
,
}
impl
Iterator
for
Vars
{
type
Item
=
(
String
,
String
)
;
fn
next
(
&
mut
self
)
->
Option
<
(
String
,
String
)
>
{
self
.
inner
.
next
(
)
}
}
/// Returns a snapshot iterator over the environment variables.
pub
fn
vars
(
)
->
Vars
{
let
snapshot
:
crate
::
alloc
::
vec
::
Vec
<
(
String
,
String
)
>
=
env_map
(
)
.
lock
(
)
.
unwrap
(
)
.
iter
(
)
.
map
(
|
(
k
,
v
)
|
(
k
.
clone
(
)
,
v
.
clone
(
)
)
)
.
collect
(
)
;
Vars
{
inner
:
snapshot
.
into_iter
(
)
,
}
}
/// The error type for [`var`].
#
[
derive
(
Debug
,
PartialEq
,
Eq
,
Clone
)
]
pub
enum
VarError
{
/// The variable was not set.
NotPresent
,
}
impl
fmt
::
Display
for
VarError
{
fn
fmt
(
&
self
,
f
:
&
mut
fmt
::
Formatter
<
'
_
>
)
-> fmt
::
Result
{
match
self
{
VarError
::
NotPresent
=> f
.
write_str
(
"environment variable not found"
)
,
}
}
}
impl
core
::
error
::
Error
for
VarError
{
}
/// Fetch the environment variable `key`. Mirrors `std::env::var`.
pub
fn
var
(
key
:
&
str
)
->
Result
<
String
,
VarError
>
{
env_map
(
)
.
lock
(
)
.
unwrap
(
)
.
get
(
key
)
.
cloned
(
)
.
ok_or
(
VarError
::
NotPresent
)
}
/// Set the environment variable `key` to `value`.
pub
fn
set_var
<
K
:
AsRef
<
str
>
,
V
:
AsRef
<
str
>
>
(
key
:
K
,
value
:
V
)
{
env_map
(
)
.
lock
(
)
.
unwrap
(
)
.
insert
(
key
.
as_ref
(
)
.
into
(
)
,
value
.
as_ref
(
)
.
into
(
)
)
;
}
/// Remove the environment variable `key`.
pub
fn
remove_var
<
K
:
AsRef
<
str
>
>
(
key
:
K
)
{
env_map
(
)
.
lock
(
)
.
unwrap
(
)
.
remove
(
key
.
as_ref
(
)
)
;
}
/// Returns the current working directory.
pub
fn
current_dir
(
)
->
crate
::
io
::
Result
<
crate
::
path
::
PathBuf
>
{
let
mut
buf =
[
0u8
;
4096
]
;
crate
::
syscall
::
getcwd
(
&
mut
buf
)
.
map_err
(
crate
::
io
::
Error
::
from
)
?
;
let
end = buf
.
iter
(
)
.
position
(
|
&
b| b ==
0
)
.
unwrap_or
(
buf
.
len
(
)
)
;
Ok
(
crate
::
path
::
PathBuf
::
from
(
String
::
from_utf8_lossy
(
&
buf
[
..end
]
)
.
into_owned
(
)
,
)
)
}
/// Change the current working directory.
pub
fn
set_current_dir
<
P
:
AsRef
<
crate
::
path
::
Path
>
>
(
path
:
P
)
->
crate
::
io
::
Result
<
(
)
>
{
let
c =
crate
::
ffi
::
CString
::
new
(
path
.
as_ref
(
)
.
as_str
(
)
.
as_bytes
(
)
)
.
map_err
(
|_|
crate
::
io
::
Error
::
from
(
crate
::
io
::
ErrorKind
::
InvalidInput
)
)
?
;
crate
::
syscall
::
chdir
(
&
c
)
.
map_err
(
crate
::
io
::
Error
::
from
)
}
/// Returns the OS temporary-files directory (`$TMPDIR`, else `/tmp`).
pub
fn
temp_dir
(
)
->
crate
::
path
::
PathBuf
{
match
var
(
"TMPDIR"
)
{
Ok
(
d
)
if
!d
.
is_empty
(
)
=>
crate
::
path
::
PathBuf
::
from
(
d
)
,
_ =>
crate
::
path
::
PathBuf
::
from
(
"/tmp"
)
,
}
}
You can’t perform that action at this time.