Visual Studio Code, rebuilt in Rust
Rust
// Used by port/tools/bench: swiftc -O port/tools/bench-memory.swift -o <bin>
// <bin> watch <pid>: samples the process tree under <pid> until SIGTERM, then prints one line
// "<peak tree footprint> <peak tree RSS> <sum of per-process peak footprints> <sum of per-process peak RSS>
// <settled footprint> <settled RSS> (MiB) <max pressure level> <max compressor MiB> <max swap MiB> <max 1-min load>"
// and one "<pid> <footprint MiB>" line per process of the tree at SIGTERM.
// <bin> selftest: checks the tree and peak bookkeeping on made-up samples.
// A scan reads every process of the tree with proc_pid_rusage: every 250 ms, and at once when a process of the tree
// forks or exits (kqueue), so a git or tsserver child is seen while it lives and read again as a zombie before its
// parent reaps it. A process stays in the tree after its parent exits (launchd adopts it), until it exits itself.
import Darwin
struct ProcessKey: Hashable {
let pid: pid_t
let start: UInt64
}
struct Listed {
let key: ProcessKey
let parent: pid_t
var zombie = false
}
struct Usage {
let footprint: UInt64
let lifetimeMaxFootprint: UInt64
let resident: UInt64
}
struct Peaks {
var members: Set<ProcessKey>
var treeFootprint: UInt64 = 0
var treeResident: UInt64 = 0
var processFootprint: [ProcessKey: UInt64] = [:]
var processResident: [ProcessKey: UInt64] = [:]
var settled: [ProcessKey: Usage] = [:]
init(root: ProcessKey) {
members = [root]
}
// Members are the processes still listed that were members, or whose parent is one; the tree sums are of one scan.
mutating func scan(_ listed: [Listed], usage: (ProcessKey) -> Usage?) {
let live = Set(listed.map(\.key))
let zombies = Set(listed.filter(\.zombie).map(\.key))
members = members.intersection(live)
var grew = true
while grew {
grew = false
let parents = Set(members.map(\.pid))
for process in listed where !members.contains(process.key) && parents.contains(process.parent) {
members.insert(process.key)
grew = true
}
}
var footprint: UInt64 = 0
var resident: UInt64 = 0
settled = [:]
for key in members {
guard let read = usage(key) else { continue }
record(key, read)
// An exited process keeps its last numbers until reaped, but its memory is already free.
if zombies.contains(key) { continue }
settled[key] = read
footprint += read.footprint
resident += read.resident
}
treeFootprint = max(treeFootprint, footprint)
treeResident = max(treeResident, resident)
}
mutating func record(_ key: ProcessKey, _ read: Usage) {
processFootprint[key] = max(processFootprint[key] ?? 0, read.lifetimeMaxFootprint, read.footprint)
processResident[key] = max(processResident[key] ?? 0, read.resident)
}
}
func listProcesses() -> [Listed] {
var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0]
var size = 0
precondition(sysctl(&mib, 4, nil, &size, nil, 0) == 0)
// Processes start between the two calls: room for 64 more.
size += 64 * MemoryLayout<kinfo_proc>.stride
var procs = [kinfo_proc](repeating: kinfo_proc(), count: size / MemoryLayout<kinfo_proc>.stride)
precondition(sysctl(&mib, 4, &procs, &size, nil, 0) == 0)
return procs.prefix(size / MemoryLayout<kinfo_proc>.stride).map { proc in
let start = proc.kp_proc.p_un.__p_starttime
return Listed(
key: ProcessKey(pid: proc.kp_proc.p_pid, start: UInt64(start.tv_sec) * 1_000_000 + UInt64(start.tv_usec)),
parent: proc.kp_eproc.e_ppid, zombie: proc.kp_proc.p_stat == SZOMB)
}
}
// Works on zombies too: the kernel keeps their rusage until the parent reaps them.
func readUsage(_ pid: pid_t) -> Usage? {
var info = rusage_info_v4()
let status = withUnsafeMutablePointer(to: &info) {
$0.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(pid, RUSAGE_INFO_V4, $0) }
}
guard status == 0 else { return nil }
return Usage(footprint: info.ri_phys_footprint, lifetimeMaxFootprint: info.ri_lifetime_max_phys_footprint, resident: info.ri_resident_size)
}
func sysctlValue<T: BitwiseCopyable>(_ name: String, _ initial: T) -> T {
var value = initial
var size = MemoryLayout<T>.size
precondition(sysctlbyname(name, &value, &size, nil, 0) == 0)
return value
}
func compressorBytes() -> UInt64 {
var stats = vm_statistics64()
var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64>.size / MemoryLayout<integer_t>.size)
let status = withUnsafeMutablePointer(to: &stats) {
$0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count) }
}
precondition(status == KERN_SUCCESS)
return UInt64(stats.compressor_page_count) * UInt64(vm_kernel_page_size)
}
func mib(_ bytes: UInt64) -> String {
String(Int((Double(bytes) / 1_048_576).rounded()))
}
var stopRequested: sig_atomic_t = 0
func watch(_ root: pid_t) {
guard let rootKey = listProcesses().first(where: { $0.key.pid == root })?.key else {
fputs("bench-memory: no process \(root)\n", stderr)
exit(1)
}
signal(SIGTERM) { _ in stopRequested = 1 }
var peaks = Peaks(root: rootKey)
var pressure: Int32 = 0
var compressor: UInt64 = 0
var swap: UInt64 = 0
var load = 0.0
let queue = kqueue()
var watched = Set<ProcessKey>()
var events = Array(repeating: kevent(), count: 64)
var timeout = timespec(tv_sec: 0, tv_nsec: 250_000_000)
while true {
let stopping = stopRequested != 0
peaks.scan(listProcesses()) { readUsage($0.pid) }
pressure = max(pressure, sysctlValue("kern.memorystatus_vm_pressure_level", Int32(0)))
compressor = max(compressor, compressorBytes())
swap = max(swap, sysctlValue("vm.swapusage", xsw_usage()).xsu_used)
var loads = [0.0]
getloadavg(&loads, 1)
load = max(load, loads[0])
if stopping { break }
var changes = Array(repeating: kevent(), count: 0)
for key in peaks.members.subtracting(watched) {
watched.insert(key)
changes.append(kevent(ident: UInt(key.pid), filter: Int16(EVFILT_PROC), flags: UInt16(EV_ADD | EV_ONESHOT), fflags: UInt32(NOTE_EXIT) | UInt32(NOTE_FORK), data: 0, udata: nil))
}
// A process that exited before EV_ADD returns ESRCH as an error event: the next scan drops it.
let count = kevent(queue, changes, Int32(changes.count), &events, Int32(events.count), &timeout)
for event in events.prefix(max(Int(count), 0)) where event.flags & UInt16(EV_ERROR) == 0 {
let pid = pid_t(event.ident)
guard let key = peaks.members.first(where: { $0.pid == pid }) else { continue }
if event.fflags & UInt32(NOTE_EXIT) != 0, let read = readUsage(pid) {
peaks.record(key, read)
} else if event.fflags & UInt32(NOTE_EXIT) == 0 {
watched.remove(key)
}
}
}
let settledFootprint = peaks.settled.values.reduce(0) { $0 + $1.footprint }
let settledResident = peaks.settled.values.reduce(0) { $0 + $1.resident }
print([
mib(peaks.treeFootprint), mib(peaks.treeResident),
mib(peaks.processFootprint.values.reduce(0, +)), mib(peaks.processResident.values.reduce(0, +)),
mib(settledFootprint), mib(settledResident),
String(pressure), mib(compressor), mib(swap), String((load * 10).rounded() / 10),
].joined(separator: " "))
for (key, read) in peaks.settled {
print(key.pid, mib(read.footprint))
}
}
func selftest() {
let root = ProcessKey(pid: 10, start: 1)
let child = ProcessKey(pid: 11, start: 2)
let git = ProcessKey(pid: 12, start: 3)
let grandchild = ProcessKey(pid: 13, start: 4)
let stranger = ProcessKey(pid: 20, start: 5)
let reused = ProcessKey(pid: 12, start: 9)
let mb: UInt64 = 1_048_576
var peaks = Peaks(root: root)
// Scan 1: root, child, git under child, grandchild listed before its parent; a stranger outside the tree.
peaks.scan([
Listed(key: grandchild, parent: 11), Listed(key: root, parent: 1), Listed(key: child, parent: 10),
Listed(key: git, parent: 11), Listed(key: stranger, parent: 1),
]) { key in
switch key {
case root: Usage(footprint: 100 * mb, lifetimeMaxFootprint: 150 * mb, resident: 200 * mb)
case child: Usage(footprint: 50 * mb, lifetimeMaxFootprint: 50 * mb, resident: 60 * mb)
case git: Usage(footprint: 30 * mb, lifetimeMaxFootprint: 40 * mb, resident: 35 * mb)
case grandchild: Usage(footprint: 5 * mb, lifetimeMaxFootprint: 5 * mb, resident: 6 * mb)
default: Usage(footprint: 999 * mb, lifetimeMaxFootprint: 999 * mb, resident: 999 * mb)
}
}
precondition(peaks.members == [root, child, git, grandchild])
precondition(peaks.treeFootprint == 185 * mb && peaks.treeResident == 301 * mb)
// git exits and is read once more as a zombie with a higher kernel peak.
peaks.record(git, Usage(footprint: 0, lifetimeMaxFootprint: 70 * mb, resident: 0))
// Scan 2: child is a zombie, grandchild is adopted by launchd and stays; git's pid is reused by an unrelated process.
peaks.scan([
Listed(key: root, parent: 1), Listed(key: child, parent: 10, zombie: true), Listed(key: grandchild, parent: 1), Listed(key: reused, parent: 1),
Listed(key: stranger, parent: 1),
]) { key in
key == root
? Usage(footprint: 120 * mb, lifetimeMaxFootprint: 160 * mb, resident: 210 * mb)
: Usage(footprint: 8 * mb, lifetimeMaxFootprint: 8 * mb, resident: 9 * mb)
}
precondition(peaks.members == [root, child, grandchild])
// The tree peak stays the larger sum of one scan (scan 1), not the sum of the maxima.
precondition(peaks.treeFootprint == 185 * mb && peaks.treeResident == 301 * mb)
// Per-process peaks: root 160, child 50, git 70, grandchild 8.
precondition(peaks.processFootprint.values.reduce(0, +) == 288 * mb)
precondition(peaks.processResident.values.reduce(0, +) == 314 * mb)
precondition(peaks.settled.keys.sorted { $0.pid < $1.pid } == [root, grandchild])
print("bench-memory selftest: ok")
}
let args = CommandLine.arguments
switch (args.count, args.dropFirst().first) {
case (3, "watch"):
watch(pid_t(args[2])!)
case (2, "selftest"):
selftest()
default:
fputs("usage: bench-memory watch <pid> | selftest\n", stderr)
exit(2)
}