Skip to main content

nodejs/stdlib/
os.rs

1//! Node `os` module. Values that Node derives from the host (platform, arch,
2//! hostname, home/tmp dirs, endianness, EOL) are returned faithfully; the
3//! machine-specific numeric readings (`cpus`, `totalmem`, `freemem`, `loadavg`,
4//! `uptime`) return best-effort placeholders (not fuzzed — they vary per host on
5//! reference Node too).
6
7use crate::host::with_host;
8use fusevm::Value;
9use indexmap::IndexMap;
10
11pub const METHODS: &[&str] = &[
12    "platform",
13    "arch",
14    "type",
15    "release",
16    "hostname",
17    "homedir",
18    "tmpdir",
19    "endianness",
20    "cpus",
21    "totalmem",
22    "freemem",
23    "uptime",
24    "loadavg",
25    "userInfo",
26    "networkInterfaces",
27    "version",
28    "machine",
29    "availableParallelism",
30    "getPriority",
31    "setPriority",
32];
33
34/// `os.EOL` constant.
35pub fn constant(name: &str) -> Option<Value> {
36    match name {
37        "EOL" => Some(with_host(|h| h.new_str("\n"))),
38        "devNull" => Some(with_host(|h| h.new_str("/dev/null"))),
39        // os.constants.signals (POSIX signal numbers) + priority levels.
40        // Every number comes from `libc`, so it is the one THIS platform uses:
41        // the signal table was a hardcoded list of macOS values, which made
42        // `SIGUSR1` 30 (Linux uses 10) and `SIGSTOP` 17 (Linux uses 19) on
43        // every Linux host. `errno` and `dlopen` were missing entirely.
44        "constants" => {
45            // Each sub-table allocates, so it is built BEFORE the borrow below
46            // rather than inside it.
47            let sig = super::constants::object(&super::constants::signals());
48            // node freezes the signal table (only that one).
49            with_host(|h| h.seal_object(&sig, true));
50            let prio = super::constants::object(&super::constants::priority());
51            let errno = super::constants::object(&super::constants::errno());
52            let dlopen = super::constants::object(&super::constants::dlopen());
53            Some(with_host(|h| {
54                let mut m = indexmap::IndexMap::new();
55                m.insert("UV_UDP_REUSEADDR".to_string(), Value::Float(4.0));
56                m.insert("dlopen".to_string(), dlopen);
57                m.insert("errno".to_string(), errno);
58                m.insert("signals".to_string(), sig);
59                m.insert("priority".to_string(), prio);
60                h.new_object(m)
61            }))
62        }
63        _ => None,
64    }
65}
66
67/// Node's `process.platform`/`os.platform()` string for the build target.
68pub fn platform() -> &'static str {
69    match std::env::consts::OS {
70        "macos" => "darwin",
71        "windows" => "win32",
72        other => other,
73    }
74}
75
76/// Node's `os.arch()`/`process.arch` string for the build target.
77pub fn arch() -> &'static str {
78    match std::env::consts::ARCH {
79        "aarch64" => "arm64",
80        "x86_64" => "x64",
81        other => other,
82    }
83}
84
85pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
86    // An `os.<fn>[Symbol.toPrimitive]`: the function's own result.
87    if let Some(m) = method.strip_prefix("@@toPrimitive:") {
88        return call(m, &[]);
89    }
90    let s = |v: &str| Ok(with_host(|h| h.new_str(v)));
91    Some(match method {
92        "platform" => s(platform()),
93        "arch" => s(arch()),
94        "machine" => s(std::env::consts::ARCH),
95        "type" => s(match std::env::consts::OS {
96            "macos" => "Darwin",
97            "linux" => "Linux",
98            "windows" => "Windows_NT",
99            other => other,
100        }),
101        "release" => s(""),
102        "version" => s(""),
103        "hostname" => s(&hostname()),
104        "homedir" => s(&dirs::home_dir()
105            .map(|p| p.to_string_lossy().into_owned())
106            .unwrap_or_default()),
107        "tmpdir" => s(std::env::temp_dir().to_string_lossy().trim_end_matches('/')),
108        "endianness" => s(if cfg!(target_endian = "big") {
109            "BE"
110        } else {
111            "LE"
112        }),
113        // Physical memory, from `sysconf`. Answering 0 is not a neutral
114        // placeholder: `os.totalmem()` is read to size caches and worker pools,
115        // and zero bytes of RAM is a value no machine reports.
116        "totalmem" => Ok(Value::Float(phys_bytes(libc::_SC_PHYS_PAGES))),
117        "freemem" => Ok(Value::Float(free_bytes())),
118        "uptime" => Ok(Value::Float(uptime_secs())),
119        "cpus" => Ok(cpus()),
120        // Real 1/5/15-minute load averages via `getloadavg(3)`.
121        "loadavg" => {
122            let mut avg = [0f64; 3];
123            // SAFETY: writes at most 3 doubles into a 3-element buffer.
124            let n = unsafe { libc::getloadavg(avg.as_mut_ptr(), 3) };
125            let items: Vec<Value> = if n == 3 {
126                avg.iter().map(|v| Value::Float(*v)).collect()
127            } else {
128                vec![Value::Float(0.0); 3]
129            };
130            Ok(with_host(|h| h.new_array(items)))
131        }
132        "networkInterfaces" => Ok(network_interfaces()),
133        "userInfo" => user_info(args),
134        // Logical CPU count (Node uses libuv's available parallelism).
135        "availableParallelism" => {
136            let n = std::thread::available_parallelism()
137                .map(|n| n.get())
138                .unwrap_or(1);
139            Ok(Value::Float(n as f64))
140        }
141        // `os.getPriority([pid])` — the nice value of `pid` (0 = current process).
142        "getPriority" => (|| -> Result<Value, String> {
143            let pid = match args.first() {
144                None | Some(Value::Undef) => 0,
145                Some(v) => {
146                    super::validate_integer_in(v, "pid", -2_147_483_648.0, 2_147_483_647.0)? as i32
147                }
148            };
149            // `getpriority` returns -1 for a nice value of -1 AND for an error,
150            // so errno is cleared first and read after (libuv's `uv_os_getpriority`).
151            // SAFETY: pure query; PRIO_PROCESS with a pid.
152            let prio = unsafe {
153                *errno_location() = 0;
154                libc::getpriority(libc::PRIO_PROCESS as _, pid as _)
155            };
156            if prio == -1 && std::io::Error::last_os_error().raw_os_error().unwrap_or(0) != 0 {
157                return Err(system_error(
158                    "uv_os_getpriority",
159                    std::io::Error::last_os_error(),
160                ));
161            }
162            Ok(Value::Float(prio as f64))
163        })(),
164        // `os.setPriority([pid, ]priority)` — best-effort (needs privilege to lower
165        // the nice value); returns undefined.
166        "setPriority" => (|| -> Result<Value, String> {
167            // `setPriority(priority)` or `setPriority(pid, priority)`.
168            let (pid_v, prio_v) = if args.len() >= 2 {
169                (Some(args[0].clone()), args[1].clone())
170            } else {
171                (None, args.first().cloned().unwrap_or(Value::Undef))
172            };
173            let pid = match pid_v {
174                Some(v) => {
175                    super::validate_integer_in(&v, "pid", -2_147_483_648.0, 2_147_483_647.0)? as i32
176                }
177                None => 0,
178            };
179            let prio = super::validate_integer_in(&prio_v, "priority", -20.0, 19.0)? as i32;
180            // SAFETY: PRIO_PROCESS with a pid and nice value; failure returns -1.
181            if unsafe { libc::setpriority(libc::PRIO_PROCESS as _, pid as _, prio as _) } != 0 {
182                return Err(system_error(
183                    "uv_os_setpriority",
184                    std::io::Error::last_os_error(),
185                ));
186            }
187            Ok(Value::Undef)
188        })(),
189        _ => return None,
190    })
191}
192
193fn hostname() -> String {
194    std::process::Command::new("hostname")
195        .output()
196        .ok()
197        .and_then(|o| String::from_utf8(o.stdout).ok())
198        .map(|s| s.trim().to_string())
199        .unwrap_or_default()
200}
201
202/// `os.userInfo([{ encoding }])`: libuv's `uv_os_get_passwd` — the password
203/// database entry for the effective uid, in node's key order `uid, gid,
204/// username, homedir, shell`, the strings as Buffers under `encoding: 'buffer'`.
205/// It read ``/``/`` and reported uid and gid as -1.
206fn user_info(args: &[Value]) -> Result<Value, String> {
207    let as_buffer = match args.first() {
208        Some(o) if with_host(|h| h.type_of(o)) == "object" && !with_host(|h| h.is_null(o)) => {
209            let e = crate::builtins::get_property(o, "encoding")?;
210            with_host(|h| h.as_str(&e)).as_deref() == Some("buffer")
211        }
212        _ => false,
213    };
214    // SAFETY: `getpwuid_r` fills `pw` with pointers into `buf`, which outlives
215    // every read below.
216    let uid = unsafe { libc::geteuid() };
217    let mut pw: libc::passwd = unsafe { std::mem::zeroed() };
218    let mut buf = vec![0 as libc::c_char; 16384];
219    let mut out: *mut libc::passwd = std::ptr::null_mut();
220    let rc = unsafe { libc::getpwuid_r(uid, &mut pw, buf.as_mut_ptr(), buf.len(), &mut out) };
221    if rc != 0 || out.is_null() {
222        let e = if rc != 0 {
223            std::io::Error::from_raw_os_error(rc)
224        } else {
225            std::io::Error::from_raw_os_error(libc::ENOENT)
226        };
227        return Err(system_error("uv_os_get_passwd", e));
228    }
229    let text = |p: *const libc::c_char| -> Vec<u8> {
230        if p.is_null() {
231            return Vec::new();
232        }
233        unsafe { std::ffi::CStr::from_ptr(p) }.to_bytes().to_vec()
234    };
235    let (name, dir, shell) = (text(pw.pw_name), text(pw.pw_dir), text(pw.pw_shell));
236    let field = |bytes: Vec<u8>| -> Value {
237        if as_buffer {
238            super::buffer::from_bytes(&bytes)
239        } else {
240            with_host(|h| h.new_str(String::from_utf8_lossy(&bytes).into_owned()))
241        }
242    };
243    let (name, dir, shell) = (field(name), field(dir), field(shell));
244    Ok(with_host(|h| {
245        let mut m = IndexMap::new();
246        m.insert("uid".into(), Value::Float(f64::from(pw.pw_uid)));
247        m.insert("gid".into(), Value::Float(f64::from(pw.pw_gid)));
248        m.insert("username".into(), name);
249        m.insert("homedir".into(), dir);
250        m.insert("shell".into(), shell);
251        h.new_object(m)
252    }))
253}
254
255/// The calling thread's `errno`.
256#[cfg(target_os = "macos")]
257unsafe fn errno_location() -> *mut libc::c_int {
258    libc::__error()
259}
260#[cfg(not(target_os = "macos"))]
261unsafe fn errno_location() -> *mut libc::c_int {
262    libc::__errno_location()
263}
264
265/// node's `ERR_SYSTEM_ERROR` (`SystemError`) for a failed libuv call: `code`,
266/// then `info` (`{ errno, code, message, syscall }`), `errno` and `syscall`,
267/// named `SystemError` and printed `SystemError [ERR_SYSTEM_ERROR]: …`. It is
268/// raised as the pending exception; the returned string is its message.
269fn system_error(syscall: &str, e: std::io::Error) -> String {
270    let code = super::fs::libuv_code(&e);
271    let (errno, reason) = super::util::errno_by_name(code).unwrap_or((libc::EIO, "i/o error"));
272    let msg = format!("A system error occurred: {syscall} returned {code} ({reason})");
273    let full = crate::host::coded_error("Error", "ERR_SYSTEM_ERROR", &msg);
274    with_host(|h| {
275        let err = crate::builtins::synth_error(h, &full);
276        let info = {
277            let mut m = IndexMap::new();
278            m.insert("errno".into(), Value::Float(-f64::from(errno)));
279            m.insert("code".into(), h.new_str(code));
280            m.insert("message".into(), h.new_str(reason));
281            m.insert("syscall".into(), h.new_str(syscall));
282            h.new_object(m)
283        };
284        let (name, stack, sys) = (
285            h.new_str("SystemError"),
286            h.new_str(format!("SystemError [ERR_SYSTEM_ERROR]: {msg}")),
287            h.new_str(syscall),
288        );
289        if let Some(crate::host::JsObj::Object(p)) = h.get_mut(&err) {
290            p.insert("info".into(), info);
291            p.insert("errno".into(), Value::Float(-f64::from(errno)));
292            p.insert("syscall".into(), sys);
293            p.insert("name".into(), name);
294            p.insert("stack".into(), stack);
295        }
296        h.hide_prop(&err, "name");
297        h.exc = Some(err);
298    });
299    full
300}
301
302/// Bytes of physical memory behind a `sysconf` page count. Both platforms this
303/// targets expose `_SC_PHYS_PAGES`; anything that does not answers 0, which is
304/// what the whole family used to do unconditionally.
305fn phys_bytes(name: libc::c_int) -> f64 {
306    // SAFETY: `sysconf` reads a constant and returns a long; -1 signals absent.
307    let pages = unsafe { libc::sysconf(name) };
308    let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
309    if pages <= 0 || page <= 0 {
310        return 0.0;
311    }
312    pages as f64 * page as f64
313}
314
315/// Free physical memory. Linux has a `sysconf` for it; macOS does not, so the
316/// page counts come from the Mach VM statistics the same way libuv reads them.
317#[cfg(target_os = "linux")]
318fn free_bytes() -> f64 {
319    phys_bytes(libc::_SC_AVPHYS_PAGES)
320}
321
322#[cfg(target_os = "macos")]
323fn free_bytes() -> f64 {
324    // `vm.page_free_count` rather than Mach's `host_statistics64`:
325    // `libc::mach_host_self` is deprecated in favour of a separate crate, and
326    // this reads the same counter through the `sysctl` path already used here.
327    let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
328    if page <= 0 {
329        return 0.0;
330    }
331    // libuv counts the free list PLUS the speculative pages, which the kernel
332    // hands back on demand — free alone reports roughly a third of what node
333    // does on the same machine.
334    let free = sysctl_u32(c"vm.page_free_count").unwrap_or(0) as f64;
335    let spec = sysctl_u32(c"vm.page_speculative_count").unwrap_or(0) as f64;
336    (free + spec) * page as f64
337}
338
339#[cfg(not(any(target_os = "linux", target_os = "macos")))]
340fn free_bytes() -> f64 {
341    0.0
342}
343
344/// Seconds since boot.
345#[cfg(target_os = "linux")]
346fn uptime_secs() -> f64 {
347    std::fs::read_to_string("/proc/uptime")
348        .ok()
349        .and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok())
350        .unwrap_or(0.0)
351}
352
353#[cfg(target_os = "macos")]
354fn uptime_secs() -> f64 {
355    let mut mib = [libc::CTL_KERN, libc::KERN_BOOTTIME];
356    let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
357    let mut len = std::mem::size_of::<libc::timeval>();
358    // SAFETY: `sysctl` writes at most `len` bytes into `tv`.
359    let rc = unsafe {
360        libc::sysctl(
361            mib.as_mut_ptr(),
362            mib.len() as u32,
363            &mut tv as *mut _ as *mut libc::c_void,
364            &mut len,
365            std::ptr::null_mut(),
366            0,
367        )
368    };
369    if rc != 0 || tv.tv_sec == 0 {
370        return 0.0;
371    }
372    let now = std::time::SystemTime::now()
373        .duration_since(std::time::UNIX_EPOCH)
374        .map(|d| d.as_secs_f64())
375        .unwrap_or(0.0);
376    (now - tv.tv_sec as f64).max(0.0).floor()
377}
378
379#[cfg(not(any(target_os = "linux", target_os = "macos")))]
380fn uptime_secs() -> f64 {
381    0.0
382}
383
384/// `os.cpus()` — one entry per logical core, each with the CPU's model string,
385/// its nominal speed in MHz, and the scheduler's time counters.
386///
387/// It answered an EMPTY array, which is the shape `os.cpus().length` is read
388/// for: sizing a worker pool off zero cores, or `|| 1` masking it.
389fn cpus() -> Value {
390    let n = std::thread::available_parallelism()
391        .map(|n| n.get())
392        .unwrap_or(1);
393    let model = cpu_model();
394    let speed = cpu_speed_mhz();
395    with_host(|h| {
396        let items: Vec<Value> = (0..n)
397            .map(|_| {
398                let mut times = IndexMap::new();
399                // The per-core counters need Mach's `host_processor_info` on
400                // macOS and `/proc/stat` on Linux; libuv reads them per core and
401                // this does not, so they are reported as zero rather than
402                // invented. The COUNT, model and speed are real.
403                for k in ["user", "nice", "sys", "idle", "irq"] {
404                    times.insert(k.to_string(), Value::Float(0.0));
405                }
406                let times = h.new_object(times);
407                let mut m = IndexMap::new();
408                m.insert("model".into(), h.new_str(model.clone()));
409                m.insert("speed".into(), Value::Float(speed));
410                m.insert("times".into(), times);
411                h.new_object(m)
412            })
413            .collect();
414        h.new_array(items)
415    })
416}
417
418#[cfg(target_os = "macos")]
419fn cpu_model() -> String {
420    sysctl_string(c"machdep.cpu.brand_string").unwrap_or_else(|| "unknown".into())
421}
422
423#[cfg(target_os = "linux")]
424fn cpu_model() -> String {
425    std::fs::read_to_string("/proc/cpuinfo")
426        .ok()
427        .and_then(|s| {
428            s.lines()
429                .find(|l| l.starts_with("model name") || l.starts_with("Model"))
430                .and_then(|l| l.split_once(':'))
431                .map(|(_, v)| v.trim().to_string())
432        })
433        .unwrap_or_else(|| "unknown".into())
434}
435
436#[cfg(not(any(target_os = "linux", target_os = "macos")))]
437fn cpu_model() -> String {
438    "unknown".into()
439}
440
441#[cfg(target_os = "macos")]
442fn cpu_speed_mhz() -> f64 {
443    // Apple Silicon does not expose `hw.cpufrequency`; libuv reports 0 there
444    // too rather than guessing.
445    sysctl_u64(c"hw.cpufrequency").map_or(0.0, |hz| (hz / 1_000_000) as f64)
446}
447
448#[cfg(target_os = "linux")]
449fn cpu_speed_mhz() -> f64 {
450    std::fs::read_to_string("/proc/cpuinfo")
451        .ok()
452        .and_then(|s| {
453            s.lines()
454                .find(|l| l.starts_with("cpu MHz"))
455                .and_then(|l| l.split_once(':'))
456                .and_then(|(_, v)| v.trim().parse::<f64>().ok())
457        })
458        .map(|f| f.round())
459        .unwrap_or(0.0)
460}
461
462#[cfg(not(any(target_os = "linux", target_os = "macos")))]
463fn cpu_speed_mhz() -> f64 {
464    0.0
465}
466
467#[cfg(target_os = "macos")]
468fn sysctl_string(name: &std::ffi::CStr) -> Option<String> {
469    let mut len: usize = 0;
470    // SAFETY: a null buffer asks only for the length.
471    if unsafe {
472        libc::sysctlbyname(
473            name.as_ptr(),
474            std::ptr::null_mut(),
475            &mut len,
476            std::ptr::null_mut(),
477            0,
478        )
479    } != 0
480        || len == 0
481    {
482        return None;
483    }
484    let mut buf = vec![0u8; len];
485    // SAFETY: writes at most `len` bytes into a buffer of that size.
486    if unsafe {
487        libc::sysctlbyname(
488            name.as_ptr(),
489            buf.as_mut_ptr() as *mut libc::c_void,
490            &mut len,
491            std::ptr::null_mut(),
492            0,
493        )
494    } != 0
495    {
496        return None;
497    }
498    buf.pop();
499    String::from_utf8(buf).ok()
500}
501
502#[cfg(target_os = "macos")]
503fn sysctl_u32(name: &std::ffi::CStr) -> Option<u32> {
504    let mut out: u32 = 0;
505    let mut len = std::mem::size_of::<u32>();
506    // SAFETY: writes at most 4 bytes into `out`.
507    let rc = unsafe {
508        libc::sysctlbyname(
509            name.as_ptr(),
510            &mut out as *mut _ as *mut libc::c_void,
511            &mut len,
512            std::ptr::null_mut(),
513            0,
514        )
515    };
516    (rc == 0).then_some(out)
517}
518
519#[cfg(target_os = "macos")]
520fn sysctl_u64(name: &std::ffi::CStr) -> Option<u64> {
521    let mut out: u64 = 0;
522    let mut len = std::mem::size_of::<u64>();
523    // SAFETY: writes at most 8 bytes into `out`.
524    let rc = unsafe {
525        libc::sysctlbyname(
526            name.as_ptr(),
527            &mut out as *mut _ as *mut libc::c_void,
528            &mut len,
529            std::ptr::null_mut(),
530            0,
531        )
532    };
533    (rc == 0).then_some(out)
534}
535
536/// `os.networkInterfaces()` — the addresses `getifaddrs(3)` reports, grouped by
537/// interface name, in node's shape. It answered an EMPTY object, which reads as
538/// a machine with no network at all.
539///
540/// Only IPv4 and IPv6 entries become addresses; a link-layer entry supplies the
541/// interface's MAC, which node attaches to every address of that interface.
542fn network_interfaces() -> Value {
543    let mut head: *mut libc::ifaddrs = std::ptr::null_mut();
544    // SAFETY: `getifaddrs` allocates the list; `freeifaddrs` releases it below.
545    if unsafe { libc::getifaddrs(&mut head) } != 0 {
546        return with_host(|h| h.new_object(IndexMap::new()));
547    }
548    let mut macs: std::collections::HashMap<String, String> = std::collections::HashMap::new();
549    let mut addrs: Vec<(String, IfAddr)> = Vec::new();
550    let mut cur = head;
551    while !cur.is_null() {
552        // SAFETY: the list is well-formed until `freeifaddrs`.
553        let ifa = unsafe { &*cur };
554        cur = ifa.ifa_next;
555        if ifa.ifa_name.is_null() {
556            continue;
557        }
558        // SAFETY: `ifa_name` is a NUL-terminated interface name.
559        let name = unsafe { std::ffi::CStr::from_ptr(ifa.ifa_name) }
560            .to_string_lossy()
561            .into_owned();
562        if let Some(mac) = link_mac(ifa) {
563            macs.insert(name.clone(), mac);
564            continue;
565        }
566        if let Some(a) = ip_addr(ifa) {
567            addrs.push((name, a));
568        }
569    }
570    // SAFETY: `head` came from `getifaddrs` and is freed exactly once.
571    unsafe { libc::freeifaddrs(head) };
572    with_host(|h| {
573        let mut grouped: IndexMap<String, Vec<Value>> = IndexMap::new();
574        for (name, a) in addrs {
575            let mac = macs
576                .get(&name)
577                .cloned()
578                .unwrap_or_else(|| "00:00:00:00:00:00".into());
579            let mut m = IndexMap::new();
580            m.insert("address".into(), h.new_str(a.address.clone()));
581            m.insert("netmask".into(), h.new_str(a.netmask.clone()));
582            m.insert("family".into(), h.new_str(a.family.to_string()));
583            m.insert("mac".into(), h.new_str(mac));
584            m.insert("internal".into(), Value::Bool(a.internal));
585            m.insert(
586                "cidr".into(),
587                h.new_str(format!("{}/{}", a.address, a.prefix)),
588            );
589            grouped.entry(name).or_default().push(h.new_object(m));
590        }
591        let mut out = IndexMap::new();
592        for (name, list) in grouped {
593            let arr = h.new_array(list);
594            out.insert(name, arr);
595        }
596        h.new_object(out)
597    })
598}
599
600struct IfAddr {
601    address: String,
602    netmask: String,
603    family: &'static str,
604    internal: bool,
605    prefix: u32,
606}
607
608/// The MAC of a link-layer entry, or `None` for an address entry.
609#[cfg(target_os = "macos")]
610fn link_mac(ifa: &libc::ifaddrs) -> Option<String> {
611    if ifa.ifa_addr.is_null() {
612        return None;
613    }
614    // SAFETY: `sa_family` is the first field of every `sockaddr`.
615    if unsafe { (*ifa.ifa_addr).sa_family } as i32 != libc::AF_LINK {
616        return None;
617    }
618    // SAFETY: an `AF_LINK` address is a `sockaddr_dl`.
619    let dl = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_dl) };
620    let start = dl.sdl_nlen as usize;
621    let len = dl.sdl_alen as usize;
622    if len != 6 || start + len > dl.sdl_data.len() {
623        return None;
624    }
625    let b: Vec<String> = dl.sdl_data[start..start + len]
626        .iter()
627        .map(|c| format!("{:02x}", *c as u8))
628        .collect();
629    Some(b.join(":"))
630}
631
632#[cfg(target_os = "linux")]
633fn link_mac(ifa: &libc::ifaddrs) -> Option<String> {
634    if ifa.ifa_addr.is_null() {
635        return None;
636    }
637    // SAFETY: `sa_family` is the first field of every `sockaddr`.
638    if unsafe { (*ifa.ifa_addr).sa_family } as i32 != libc::AF_PACKET {
639        return None;
640    }
641    // SAFETY: an `AF_PACKET` address is a `sockaddr_ll`.
642    let ll = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_ll) };
643    let len = ll.sll_halen as usize;
644    if len != 6 {
645        return None;
646    }
647    let b: Vec<String> = ll.sll_addr[..len]
648        .iter()
649        .map(|c| format!("{c:02x}"))
650        .collect();
651    Some(b.join(":"))
652}
653
654#[cfg(not(any(target_os = "linux", target_os = "macos")))]
655fn link_mac(_ifa: &libc::ifaddrs) -> Option<String> {
656    None
657}
658
659/// The IPv4/IPv6 address of an entry, with its netmask and prefix length.
660fn ip_addr(ifa: &libc::ifaddrs) -> Option<IfAddr> {
661    if ifa.ifa_addr.is_null() {
662        return None;
663    }
664    // SAFETY: `sa_family` is the first field of every `sockaddr`.
665    let fam = unsafe { (*ifa.ifa_addr).sa_family } as i32;
666    let internal = ifa.ifa_flags & libc::IFF_LOOPBACK as u32 != 0;
667    if fam == libc::AF_INET {
668        // SAFETY: an `AF_INET` address is a `sockaddr_in`.
669        let sin = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in) };
670        let ip = std::net::Ipv4Addr::from(u32::from_be(sin.sin_addr.s_addr));
671        let mask = if ifa.ifa_netmask.is_null() {
672            std::net::Ipv4Addr::UNSPECIFIED
673        } else {
674            // SAFETY: the netmask of an `AF_INET` entry is a `sockaddr_in`.
675            let m = unsafe { &*(ifa.ifa_netmask as *const libc::sockaddr_in) };
676            std::net::Ipv4Addr::from(u32::from_be(m.sin_addr.s_addr))
677        };
678        return Some(IfAddr {
679            address: ip.to_string(),
680            netmask: mask.to_string(),
681            family: "IPv4",
682            internal,
683            prefix: u32::from(mask).count_ones(),
684        });
685    }
686    if fam == libc::AF_INET6 {
687        // SAFETY: an `AF_INET6` address is a `sockaddr_in6`.
688        let sin = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in6) };
689        let ip = std::net::Ipv6Addr::from(sin.sin6_addr.s6_addr);
690        let mask = if ifa.ifa_netmask.is_null() {
691            std::net::Ipv6Addr::UNSPECIFIED
692        } else {
693            // SAFETY: the netmask of an `AF_INET6` entry is a `sockaddr_in6`.
694            let m = unsafe { &*(ifa.ifa_netmask as *const libc::sockaddr_in6) };
695            std::net::Ipv6Addr::from(m.sin6_addr.s6_addr)
696        };
697        let prefix: u32 = mask.octets().iter().map(|b| b.count_ones()).sum();
698        return Some(IfAddr {
699            address: ip.to_string(),
700            netmask: mask.to_string(),
701            family: "IPv6",
702            internal,
703            prefix,
704        });
705    }
706    None
707}
708
709/// The `os` functions node gives a `[Symbol.toPrimitive]` (`() => fn()`), so
710/// `` `${os.arch}` `` and `os.freemem + 0` read the value.
711pub const TO_PRIMITIVE: &[&str] = &[
712    "arch",
713    "availableParallelism",
714    "endianness",
715    "freemem",
716    "homedir",
717    "hostname",
718    "platform",
719    "release",
720    "tmpdir",
721    "totalmem",
722    "type",
723    "uptime",
724    "version",
725    "machine",
726];