Files
bun.sh/src/c.zig
Jarred Sumner 6362414d65 Bun gets a new bundler (#2312)
* alright now just gotta try running it

* fix a gajillion compiler errors

* even more code

* okay i fixed more errors

* wip

* Update launch.json

* Update string_builder.zig

* `fast_debug_build_mode` makes debug build 2x faster

* Update bundle_v2.zig

* more code!

* It bundles!

* Rename `Bun.Transpiler` to `Bun.Bundler`

* `import()` expressions almost work

* wip attempt to get import() expr to work

* Bundle namespace imports

* Attempt to fix the issue with import() unsuccessfully

* consider current working directory when resolving relative paths (#2313)

* consider current working directory when resolving relative paths

fixes #2298

* comment test

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>

* support `expect().toThrow(/pattern/)` (#2314)

- fix time-zone-dependent test failure

* fix missing `Blob` error messages on Linux (#2315)

* fix & clean up tests (#2318)

- skip flaky tests when running as `root`
- use `expect().toThrow()`
- clean up temporary files after tests

* feat(tty): add some `tty.WriteStream` methods to `process.{stdout, stderr}` (#2320)

* feat(stdio): add some `tty.WriteStream` methods

* chore(builtins): add process builtin gen'd code

* Fix docker install command

* `bun test` on macOS in GitHub Actions (#2322)

* Fixes #2323

* throw invalid parameter errors in `crypto.scryptSync` (#2331)

* throw invalid parameter errors

* remove comptime, add empty buffer function

* remove error_name comptime

* Add reference documentation for bun:test (#2327)

* Reorganize tests (#2332)

* Fix html-rewriter.test.js

* fix the wrong thing being incremented in hmr example (#2334)

* Add more test harness

* Improve Benchmarking page, small fixes (#2339)

* Improve benchmarking page

* WIP

* Add typescript instructions to hot

* Document preload in Plugins. Fix loader in plugin types.

* Fix typo

* Fix links

* run prettier

* Document openInEditor

* improve `Buffer` compatibility with Node.js (#2341)

* improve `Buffer` compatibility with Node.js

* use `memmove()`
allow `encoding` to be `undefined`

* run `bun test` after macOS builds (#2343)

* "binary" is an alias of "latin1"

Fixes https://github.com/oven-sh/bun/issues/2110

* More spec compliant `Blob.prototype.type` (#2340)

* Make `Blob.prototype. type` more spec compliant

* Add a few more checks for isNumber()

* Fix `make headers`

* Safer JSValue.isString()

* More tests for blob.slice

* Make `Blob.prototype.type` more spec compliant

* Add isASCII check

* Fix types

* Fix failing type test

* Update blob.zig

* Update blob.zig

* Fix .eql check on empty values

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>

* Fix bug in test runner

* Support `import()` expressions

* Implement `require()`

* clean up bit_set.zig slightly

* Move some things around

* misc cleanup

* Cleanup some things

* Fix a lot of stuff

* Fix `module.exports.fn = fn;` in ESM entry point

* Fix crash due when printing file

* Fix issue with class names

* Fix issue with `export default identifier`

* Update js_parser.zig

* optimization: inline single-property object acceses and arrays

* Fix undefined memory in renamed symbols list

* Handle call target

* wip

* Inline it

* Fix undefined memory issue when reclaiming blocks in ast

* Halt linking on any parse errors

* alias

* Rename `enable_bundling` to `enable_legacy_bundling`

* Workaround anonymous struct literal zig bug

* Use slower approach (without bitset) because it doesn't break after 8 symbols

* Fix incorrectly-renaming statically defined symbols

* Handle more edgecases in our bit_set fork

* Reduce number of allocations for `define`

* Do not rename unbound symbols

* Clean up dot defines a little more

* Make the generated names prettier

* Workaround runtime symbol missing issue

* Fail the build on errors

* Support export * from

* Support `--outfile`

* partially fix renaming

* fanicer symbol renaming impl

* misc, extremely revertible cleanup

* Fix up some bugs with symbol renaming

* formatting

* Update launch.json

* Parse `__PURE__` comments

* clean up simd code for pure comments

* changes to merge

* workaround runtime issue

* Fix issue with `export * as` not propagating correctly

* Make all top-level declarations `var` when bundling

* Fix missing prefix

* Fix assigning to stack copy

* Fix missing runtime symbol

* Fix bug with namespace exports

* Dramatically reduce allocations

* Update launch.json

* Add missing flags

* Update js_parser.zig

* small cleanup

* Make the export name better

* Fix unnecessary `var foo = foo`

* Implement CommonJS -> ESM conversion

* Implement module redirects

* Port esbuild bundler tests for new bundler (#2380)

* started porting esbuild tests

* clean up test names and api before moving on

* port tests using a program i wrote

* replace todo generated comment

* fix generated tests not including some files

* work on tests

* [github web editor] add define, external, inject, minifySyntax, minifyWhitespace options.

* get most of the todo comments out of the way, but expectBundled does not handle most of the cases

* continue working on esbuild tests

* use test.skip for unsupported tests

* Fixups for test runner

* Hoist imports & exports

* Fix test

* Hoist classes

* bundler test refining, 51/835

* Fix runtime require

* bundler test refining, 81/835

* bundler test refining, 93/835

* Make the test work in any timezone

* feat(expect): update toBeInstanceOf (#2396)

* feat: update instanceof binding

* fix: according to PR comments

* Rename `expectObjectTypeCount` to `expectMaxObjectTypeCount`

* Fix socket tests with connection errors (#2403)

* release pending activity with connection error handler

* unref poll_ref

* remove trailing comma

* Organize Dockerfiles for official status

* Remove test Dockerfile

* Remove old Docker workflow

* Feat(test): add toMatch (#2404)

* Fix various fetch/response/request tests (#2416)

* fix most fetch tests, skip a few

* fastGet, toValueGC, and invalid init

* bigint unreachable, range error, log process as process

* remove extra fetch_headers

* remove js_type parameter, check isObject()

* throw invalid mime type error, use enum literal

* switch back to promise rejection

* RangeError pascal case

* Fix several bugs (#2418)

* utf16 codepoint with replacement character

* Fix test failure with `TextEncoder("ascii')`

* Add missing type

* Fix Response.prototype.bodyUsed and Request.prototype.bodyUsed

* Fix bug with scrypt error not clearing

* Update server.zig

* oopsie

* 💅

* docs: Use correct url in the 'Issues' link in README header (#2420)

* Fix crash when rendering error page and the server or network is slow

* [fetch] Make the default body value `null` when unspecified

This is better aligned with the fetch spec

* Make node-net tests less flaky

* [node:net] Fix issue with `listen` callback firing before it's listening

* Always clear timers in node test harness

* Fix out of bounds access

Repro'd in Buffer tests

* Update UWS

cc @cirospaciari

* Make this test more thorough

* Hanging abort test

* 0 length body is a null stream

* Several bug fixes (#2427)

* Fix test

* Fix segfault when unexpected type is passed in `expect().toThrow`

* Fix issues with request constructor

* Don't bother cloning headers when its empty

* woops

* more tests

* fix incorrect test

* Make the fetch error messages better

* Update response.zig

* Fix test that failed on macOS

* Fix test

* Remove extra hash table lookups

* Support running dummy registry directly

cc @alexlamsl

* Update test

* Update test

* fixup

* Workaround crash in test runner

* Fixup test

* Fixup test

* Update os.test.js

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>

* Remove usages of port numbers in tests

* Set -O2 and -fno-rtti

* Remove -g

* Prevent undefined memory access

* [bun test] Implement `--rerun-each` flag to run each test N times

* Reduce number of module scopes created

* add some extra abort checks into streams (#2430)

* add some checks to avoid UAF

* avoid multiple calls to finalize if endFromJS is called more than once

* fix no-op comment

* mark as requested_end on abort

* remove requested_end from abort

* remove unnecessary check (#2432)

* Fix bug with scoped aliased dependencies in bun install on macOS

* remove `addLog`, remove `--prominent-compile-errors`

* Finish the upgrade

* Optional chaining flag

* Implement same_target_becomes_destructuring optimization

* bundler test refining, 109/835

* Reset bindings

* Support multiple entry points

* Implement `--entry-names` flag

* Use a tempdir with a better name

* prettier

* Log file name

* Update js_parser.zig

* Mark all bun builtins as external

* Make resolve errors actually errors

* Update bundler_default.test.ts

* Fix `await import(foo)`

* WIP react server components

* Do more stuff at runtime

* ✂️

* Support automatic JSX imports

* Use a module cache for now

* Update tsconfig.base.json

* Fix ThisOutsideFunctionNotRenamed

* woopsie

* moar cpu

* clamp it

* fixup

* Add a bunch of assertions

* Bun uses automatic runtime by default

* Parse Import Attributes

* Add a note about Valgrind

* Update developing.md

* Fix up code splitting for React Server Components

* Implement client component manifest

* Fix crash with --react-server-components and no client components

* Backport 4d31e3c917

* Update launch.json

* Fix for latest zig

* Workaround bug with ?[]const string

Occasionally saw alignment errors in this code

Workaround https://github.com/ziglang/zig/issues/15085

related: https://github.com/ziglang/zig/pull/15089

* switch to regular slice

* Avoid initializing named_imports and named_exports as undefined

* Reduce usages of `undefined`

* Add more assertions

* --watch wip

* Update javascript.zig

* Possibly fix the race condition

* Faster `do`

* bump allocator

* Reduce the size of `Symbol` slightly

* Alphabetically sort runtime import symbols, for determinism

* Prepare for code splitting

* handle overlapping stdout

* pure

* clean up some things

* Fix bug with `$$typeof`

* Address CommonJS -> ESM hoisting bug

* Support `"use server"` in manifest

* Implement `"use server"`

* Fix importing bun builtins when bundling

* Make `commonjs_to_esm` a feature flag, fix some splitting bugs

* ✂️

* fixme remove this

* Fix crash in longestCommonPath

* Chunking! Just need to do import paths now.

* Import paths work...now trying to figure out how to make runtime symbols work

* add workaround

* Replace `bun bun` with `bun build`

* Fix crash with dual package hazard

* Fix many CommonJS <> ESM interop bugs

* Support package.json `"sideEffects"`

also skip loading unnecessary package.json data in `bun run`

* add a not good --watch implementation

* bundler test refining, 140/831

* remove accidentally committed file

* do not return status code 1 on successful bundles

* bundler test refining, 159/830

* pass exit code to exitOrWatch

* clean up help menu

-remove two spaces to line up bun build
-moved all <r> tags to the end of the text they are colorizing
-moved other colors to the start of the text they colorize
-removed unneeded <r> tags, keeping only one at the start of the block

* importstar is fully ported

* wip

* you can run code in this branch now

* Disable this transform

* organize and document bundler tests

* Fix double import

* Fix sloppy mode function declarations

* Disable our CommonJS transform for now

* add `assertNotPresent` to make splitting cases easier

* Bump!

* Update bun.d.ts

* use import.meta.require in runtime code

* Disable this again

* Fix dirname

* Fix ESM -> CJS wrapper

* 💅

---------

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
Co-authored-by: Alex Lam S.L <alexlamsl@gmail.com>
Co-authored-by: Derrick Farris <mr.dcfarris@gmail.com>
Co-authored-by: Ashcon Partovi <ashcon@partovi.net>
Co-authored-by: Dylan Conway <35280289+dylan-conway@users.noreply.github.com>
Co-authored-by: pfg <pfg@pfg.pw>
Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
Co-authored-by: dave caruso <me@paperdave.net>
Co-authored-by: zhiyuan <32867472+zhiyuang@users.noreply.github.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Co-authored-by: Kamil Ogórek <kamil.ogorek@gmail.com>
Co-authored-by: Ciro Spaciari <ciro.spaciari@gmail.com>
2023-04-07 20:08:01 -07:00

452 lines
16 KiB
Zig

const std = @import("std");
const bun = @import("bun");
const Environment = @import("./env.zig");
const PlatformSpecific = switch (@import("builtin").target.os.tag) {
.macos => @import("./darwin_c.zig"),
.linux => @import("./linux_c.zig"),
else => struct {},
};
pub usingnamespace PlatformSpecific;
const C = std.c;
const builtin = @import("builtin");
const os = std.os;
const mem = std.mem;
const Stat = std.fs.File.Stat;
const Kind = std.fs.File.Kind;
const StatError = std.fs.File.StatError;
const errno = os.errno;
const mode_t = C.mode_t;
const libc_stat = C.Stat;
const zeroes = mem.zeroes;
pub const darwin = @import("./darwin_c.zig");
pub const linux = @import("./linux_c.zig");
pub extern "c" fn chmod([*c]const u8, mode_t) c_int;
pub extern "c" fn fchmod(std.c.fd_t, mode_t) c_int;
pub extern "c" fn umask(mode_t) mode_t;
pub extern "c" fn fchmodat(c_int, [*c]const u8, mode_t, c_int) c_int;
pub extern "c" fn fchown(std.c.fd_t, std.c.uid_t, std.c.gid_t) c_int;
pub extern "c" fn lchown(path: [*:0]const u8, std.c.uid_t, std.c.gid_t) c_int;
pub extern "c" fn chown(path: [*:0]const u8, std.c.uid_t, std.c.gid_t) c_int;
pub extern "c" fn lstat64([*c]const u8, [*c]libc_stat) c_int;
pub extern "c" fn fstat64([*c]const u8, [*c]libc_stat) c_int;
pub extern "c" fn stat64([*c]const u8, [*c]libc_stat) c_int;
pub extern "c" fn lchmod(path: [*:0]const u8, mode: mode_t) c_int;
pub extern "c" fn truncate([*:0]const u8, i64) c_int; // note: truncate64 is not a thing
pub extern "c" fn lutimes(path: [*:0]const u8, times: *const [2]std.os.timeval) c_int;
pub extern "c" fn mkdtemp(template: [*c]u8) ?[*:0]u8;
pub extern "c" fn memcmp(s1: [*c]const u8, s2: [*c]const u8, n: usize) c_int;
pub extern "c" fn memchr(s: [*]const u8, c: u8, n: usize) ?[*]const u8;
pub const lstat = lstat64;
pub const fstat = fstat64;
pub const stat = stat64;
pub extern "c" fn strchr(str: [*]const u8, char: u8) ?[*]const u8;
pub fn lstat_absolute(path: [:0]const u8) !Stat {
if (builtin.os.tag == .windows) {
@compileError("Not implemented yet");
}
var st = zeroes(libc_stat);
switch (errno(lstat64(path.ptr, &st))) {
.SUCCESS => {},
.NOENT => return error.FileNotFound,
// .EINVAL => unreachable,
.BADF => unreachable, // Always a race condition.
.NOMEM => return error.SystemResources,
.ACCES => return error.AccessDenied,
else => |err| return os.unexpectedErrno(err),
}
const atime = st.atime();
const mtime = st.mtime();
const ctime = st.ctime();
return Stat{
.inode = st.ino,
.size = @bitCast(u64, st.size),
.mode = st.mode,
.kind = switch (builtin.os.tag) {
.wasi => switch (st.filetype) {
os.FILETYPE_BLOCK_DEVICE => Kind.BlockDevice,
os.FILETYPE_CHARACTER_DEVICE => Kind.CharacterDevice,
os.FILETYPE_DIRECTORY => Kind.Directory,
os.FILETYPE_SYMBOLIC_LINK => Kind.SymLink,
os.FILETYPE_REGULAR_FILE => Kind.File,
os.FILETYPE_SOCKET_STREAM, os.FILETYPE_SOCKET_DGRAM => Kind.UnixDomainSocket,
else => Kind.Unknown,
},
else => switch (st.mode & os.S.IFMT) {
os.S.IFBLK => Kind.BlockDevice,
os.S.IFCHR => Kind.CharacterDevice,
os.S.IFDIR => Kind.Directory,
os.S.IFIFO => Kind.NamedPipe,
os.S.IFLNK => Kind.SymLink,
os.S.IFREG => Kind.File,
os.S.IFSOCK => Kind.UnixDomainSocket,
else => Kind.Unknown,
},
},
.atime = @as(i128, atime.tv_sec) * std.time.ns_per_s + atime.tv_nsec,
.mtime = @as(i128, mtime.tv_sec) * std.time.ns_per_s + mtime.tv_nsec,
.ctime = @as(i128, ctime.tv_sec) * std.time.ns_per_s + ctime.tv_nsec,
};
}
// renameatZ fails when renaming across mount points
// we assume that this is relatively uncommon
pub fn moveFileZ(from_dir: std.os.fd_t, filename: [*:0]const u8, to_dir: std.os.fd_t, destination: [*:0]const u8) !void {
std.os.renameatZ(from_dir, filename, to_dir, destination) catch |err| {
switch (err) {
error.RenameAcrossMountPoints => {
try moveFileZSlow(from_dir, filename, to_dir, destination);
},
else => {
return err;
},
}
};
}
pub fn moveFileZWithHandle(from_handle: std.os.fd_t, from_dir: std.os.fd_t, filename: [*:0]const u8, to_dir: std.os.fd_t, destination: [*:0]const u8) !void {
std.os.renameatZ(from_dir, filename, to_dir, destination) catch |err| {
switch (err) {
error.RenameAcrossMountPoints => {
try moveFileZSlowWithHandle(from_handle, to_dir, destination);
},
else => {
return err;
},
}
};
}
// On Linux, this will be fast because sendfile() supports copying between two file descriptors on disk
// macOS & BSDs will be slow because
pub fn moveFileZSlow(from_dir: std.os.fd_t, filename: [*:0]const u8, to_dir: std.os.fd_t, destination: [*:0]const u8) !void {
const in_handle = try std.os.openatZ(from_dir, filename, std.os.O.RDONLY | std.os.O.CLOEXEC, 0o600);
try moveFileZSlowWithHandle(in_handle, to_dir, destination);
}
pub fn moveFileZSlowWithHandle(in_handle: std.os.fd_t, to_dir: std.os.fd_t, destination: [*:0]const u8) !void {
const stat_ = try std.os.fstat(in_handle);
// delete if exists, don't care if it fails. it may fail due to the file not existing
// delete here because we run into weird truncation issues if we do not
// ftruncate() instead didn't work.
// this is technically racy because it could end up deleting the file without saving
std.os.unlinkatZ(to_dir, destination, 0) catch {};
const out_handle = try std.os.openatZ(to_dir, destination, std.os.O.WRONLY | std.os.O.CREAT | std.os.O.CLOEXEC, 0o022);
defer std.os.close(out_handle);
if (comptime Environment.isLinux) {
_ = std.os.system.fallocate(out_handle, 0, 0, @intCast(i64, stat_.size));
_ = try std.os.sendfile(out_handle, in_handle, 0, @intCast(usize, stat_.size), &[_]std.os.iovec_const{}, &[_]std.os.iovec_const{}, 0);
} else {
if (comptime Environment.isMac) {
// if this fails, it doesn't matter
// we only really care about read & write succeeding
PlatformSpecific.preallocate_file(
out_handle,
@intCast(std.os.off_t, 0),
@intCast(std.os.off_t, stat_.size),
) catch {};
}
var buf: [8092 * 2]u8 = undefined;
var total_read: usize = 0;
while (true) {
const read = try std.os.pread(in_handle, &buf, total_read);
total_read += read;
if (read == 0) break;
const bytes = buf[0..read];
const written = try std.os.write(out_handle, bytes);
if (written == 0) break;
}
}
_ = fchmod(out_handle, stat_.mode);
_ = fchown(out_handle, stat_.uid, stat_.gid);
}
pub fn kindFromMode(mode: os.mode_t) std.fs.File.Kind {
return switch (mode & os.S.IFMT) {
os.S.IFBLK => std.fs.File.Kind.BlockDevice,
os.S.IFCHR => std.fs.File.Kind.CharacterDevice,
os.S.IFDIR => std.fs.File.Kind.Directory,
os.S.IFIFO => std.fs.File.Kind.NamedPipe,
os.S.IFLNK => std.fs.File.Kind.SymLink,
os.S.IFREG => std.fs.File.Kind.File,
os.S.IFSOCK => std.fs.File.Kind.UnixDomainSocket,
else => .Unknown,
};
}
pub fn getSelfExeSharedLibPaths(allocator: std.mem.Allocator) error{OutOfMemory}![][:0]u8 {
const List = std.ArrayList([:0]u8);
switch (builtin.os.tag) {
.linux,
.freebsd,
.netbsd,
.dragonfly,
.openbsd,
.solaris,
=> {
var paths = List.init(allocator);
errdefer {
const slice = paths.toOwnedSlice() catch &.{};
for (slice) |item| {
allocator.free(item);
}
allocator.free(slice);
}
try os.dl_iterate_phdr(&paths, error{OutOfMemory}, struct {
fn callback(info: *os.dl_phdr_info, size: usize, list: *List) !void {
_ = size;
const name = info.dlpi_name orelse return;
if (name[0] == '/') {
const item = try list.allocator.dupeZ(u8, mem.sliceTo(name, 0));
errdefer list.allocator.free(item);
try list.append(item);
}
}
}.callback);
return try paths.toOwnedSlice();
},
.macos, .ios, .watchos, .tvos => {
var paths = List.init(allocator);
errdefer {
const slice = paths.toOwnedSlice() catch &.{};
for (slice) |item| {
allocator.free(item);
}
allocator.free(slice);
}
const img_count = std.c._dyld_image_count();
var i: u32 = 0;
while (i < img_count) : (i += 1) {
const name = std.c._dyld_get_image_name(i);
const item = try allocator.dupeZ(u8, mem.sliceTo(name, 0));
errdefer allocator.free(item);
try paths.append(item);
}
return try paths.toOwnedSlice();
},
// revisit if Haiku implements dl_iterat_phdr (https://dev.haiku-os.org/ticket/15743)
.haiku => {
var paths = List.init(allocator);
errdefer {
const slice = paths.toOwnedSlice() catch &.{};
for (slice) |item| {
allocator.free(item);
}
allocator.free(slice);
}
var b = "/boot/system/runtime_loader";
const item = try allocator.dupeZ(u8, mem.sliceTo(b, 0));
errdefer allocator.free(item);
try paths.append(item);
return try paths.toOwnedSlice();
},
else => @compileError("getSelfExeSharedLibPaths unimplemented for this target"),
}
}
/// The madvise() system call allows a process that has knowledge of its mem-ory memory
/// ory behavior to describe it to the system. The advice passed in may be
/// used by the system to alter its virtual memory paging strategy. This
/// advice may improve application and system performance. The behavior
/// specified in advice can only be one of the following values:
///
/// MADV_NORMAL Indicates that the application has no advice to give on
/// its behavior in the specified address range. This is
/// the system default behavior. This is used with
/// madvise() system call.
///
/// POSIX_MADV_NORMAL
/// Same as MADV_NORMAL but used with posix_madvise() system
/// call.
///
/// MADV_SEQUENTIAL Indicates that the application expects to access this
/// address range in a sequential manner. This is used with
/// madvise() system call.
///
/// POSIX_MADV_SEQUENTIAL
/// Same as MADV_SEQUENTIAL but used with posix_madvise()
/// system call.
///
/// MADV_RANDOM Indicates that the application expects to access this
/// address range in a random manner. This is used with
/// madvise() system call.
///
/// POSIX_MADV_RANDOM
/// Same as MADV_RANDOM but used with posix_madvise() system
/// call.
///
/// MADV_WILLNEED Indicates that the application expects to access this
/// address range soon. This is used with madvise() system
/// call.
///
/// POSIX_MADV_WILLNEED
/// Same as MADV_WILLNEED but used with posix_madvise() sys-tem system
/// tem call.
///
/// MADV_DONTNEED Indicates that the application is not expecting to
/// access this address range soon. This is used with
/// madvise() system call.
///
/// POSIX_MADV_DONTNEED
/// Same as MADV_DONTNEED but used with posix_madvise() sys-tem system
/// tem call.
///
/// MADV_FREE Indicates that the application will not need the infor-mation information
/// mation contained in this address range, so the pages may
/// be reused right away. The address range will remain
/// valid. This is used with madvise() system call.
///
/// The posix_madvise() behaves same as madvise() except that it uses values
/// with POSIX_ prefix for the advice system call argument.
pub extern "c" fn posix_madvise(ptr: *anyopaque, len: usize, advice: i32) c_int;
// System related
pub fn getFreeMemory() u64 {
if (comptime Environment.isLinux) {
return linux.get_free_memory();
} else if (comptime Environment.isMac) {
return darwin.get_free_memory();
} else {
return -1;
}
}
pub fn getTotalMemory() u64 {
if (comptime Environment.isLinux) {
return linux.get_total_memory();
} else if (comptime Environment.isMac) {
return darwin.get_total_memory();
} else {
return -1;
}
}
pub fn getSystemUptime() u64 {
if (comptime Environment.isLinux) {
return linux.get_system_uptime();
} else {
return darwin.get_system_uptime();
}
}
pub fn getSystemLoadavg() [3]f64 {
if (comptime Environment.isLinux) {
return linux.get_system_loadavg();
} else {
return darwin.get_system_loadavg();
}
}
pub fn getProcessPriority(pid_: i32) i32 {
const pid = @intCast(c_uint, pid_);
return get_process_priority(pid);
}
pub fn setProcessPriority(pid_: i32, priority_: i32) std.c.E {
if (pid_ < 0) return .SRCH;
const pid = @intCast(c_uint, pid_);
const priority = @intCast(c_int, priority_);
const code: i32 = set_process_priority(pid, priority);
if (code == -2) return .SRCH;
if (code == 0) return .SUCCESS;
const errcode = std.c.getErrno(code);
return errcode;
}
pub fn getVersion(buf: []u8) []const u8 {
if (comptime Environment.isLinux) {
return linux.get_version(buf.ptr[0..std.os.HOST_NAME_MAX]);
} else if (comptime Environment.isMac) {
return darwin.get_version(buf);
} else {
return "unknown";
}
}
pub fn getRelease(buf: []u8) []const u8 {
if (comptime Environment.isLinux) {
return linux.get_release(buf.ptr[0..std.os.HOST_NAME_MAX]);
} else if (comptime Environment.isMac) {
return darwin.get_release(buf);
} else {
return "unknown";
}
}
pub extern fn memmem(haystack: [*]const u8, haystacklen: usize, needle: [*]const u8, needlelen: usize) ?[*]const u8;
pub extern fn cfmakeraw(*std.os.termios) void;
const LazyStatus = enum {
pending,
loaded,
failed,
};
pub fn dlsymWithHandle(comptime Type: type, comptime name: [:0]const u8, comptime handle_getter: fn () ?*anyopaque) ?Type {
if (comptime @typeInfo(Type) != .Pointer) {
@compileError("dlsym must be a pointer type (e.g. ?const *fn()). Received " ++ @typeName(Type) ++ ".");
}
const Wrapper = struct {
pub var function: Type = undefined;
pub var loaded: LazyStatus = LazyStatus.pending;
};
if (Wrapper.loaded == .pending) {
const result = std.c.dlsym(@call(.always_inline, handle_getter, .{}), name);
if (result) |ptr| {
Wrapper.function = bun.cast(Type, ptr);
Wrapper.loaded = .loaded;
return Wrapper.function;
} else {
Wrapper.loaded = .failed;
return null;
}
}
if (Wrapper.loaded == .loaded) {
return Wrapper.function;
}
return null;
}
pub fn dlsym(comptime Type: type, comptime name: [:0]const u8) ?Type {
const handle_getter = struct {
const RTLD_DEFAULT = if (bun.Environment.isMac)
@intToPtr(?*anyopaque, @bitCast(usize, @as(isize, -2)))
else
@intToPtr(?*anyopaque, @as(usize, 0));
pub fn getter() ?*anyopaque {
return RTLD_DEFAULT;
}
}.getter;
return dlsymWithHandle(Type, name, handle_getter);
}
// set in c-bindings.cpp
pub extern fn get_process_priority(pid: c_uint) i32;
pub extern fn set_process_priority(pid: c_uint, priority: c_int) i32;
pub extern fn strncasecmp(s1: [*]const u8, s2: [*]const u8, n: usize) i32;
pub extern fn memmove(dest: [*]u8, src: [*]const u8, n: usize) void;