Skip to content

Instantly share code, notes, and snippets.

@tamasd
Created June 2, 2014 22:00
Show Gist options
  • Save tamasd/268223da3c6f0fb92944 to your computer and use it in GitHub Desktop.
Save tamasd/268223da3c6f0fb92944 to your computer and use it in GitHub Desktop.
A bit more readable kextstat command for Mac OS X.
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os/exec"
"regexp"
"sort"
"strconv"
"github.com/dustin/go-humanize"
)
var kextLine = regexp.MustCompile(`[\s]*([\d]+)[\s]*([\d]+)[\s]*(0x[0-9a-f]+)[\s]*(0x[0-9a-f]+)[\s]*(0x[0-9a-f]+)[\s]*([a-zA-Z._0-9]+)`)
type Kext struct {
Index uint32
Refs uint32
Address uint64
Size uint64
Wired uint64
Name string
}
func (k Kext) String() string {
str := humanize.IBytes(k.Size) + "\t"
str += k.Name
return str
}
type BySizeDesc []Kext
func (a BySizeDesc) Len() int { return len(a) }
func (a BySizeDesc) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a BySizeDesc) Less(i, j int) bool { return a[i].Size > a[j].Size }
func main() {
kextstat := exec.Command("kextstat", "-l")
out := bytes.NewBuffer(nil)
kextstat.Stdout = out
err := kextstat.Run()
if err != nil {
log.Fatal(err)
}
kexts := []Kext{}
output, _ := ioutil.ReadAll(out)
for _, m := range kextLine.FindAllStringSubmatch(string(output), -1) {
k := Kext{}
if len(m) != 7 {
log.Println("Invalid line")
continue
}
k.Index = parseuint32(m[1])
k.Refs = parseuint32(m[2])
k.Address = parseuint64(m[3])
k.Size = parseuint64(m[4])
k.Wired = parseuint64(m[5])
k.Name = m[6]
kexts = append(kexts, k)
}
sort.Sort(BySizeDesc(kexts))
for _, k := range kexts {
fmt.Println(k)
}
}
func parseuint32(s string) uint32 {
n, err := strconv.ParseUint(s, 0, 32)
if err != nil {
log.Print(err)
}
return uint32(n)
}
func parseuint64(s string) uint64 {
n, err := strconv.ParseUint(s, 0, 64)
if err != nil {
log.Print(err)
}
return uint64(n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment