//go:build linux package render import ( "bytes" "fmt" "os" "strconv" "strings" "sync" "time" "golang.org/x/sys/unix" ) // limitMemory is render-sandbox's limit on itself and so on the browser // and every process it starts: a data segment (private writable memory) // of at most MemoryLimit, soft and hard. Nothing in the sandbox can raise // it: that needs CAP_SYS_RESOURCE in the host's user namespace. The // address space is not limited: the browser reserves far more than it // uses (V8's sandbox alone is a terabyte, mapped inaccessible). func limitMemory() error { return unix.Setrlimit(unix.RLIMIT_DATA, &unix.Rlimit{Cur: MemoryLimit, Max: MemoryLimit}) } // reasonLimits is render-sandbox's "failed" reason when it cannot set // limitMemory. const reasonLimits = "limits" // memoryEvery is how often the runner sums the sandbox's memory. const memoryEvery = 100 * time.Millisecond // watchMemory sums the resident memory of every process in the sandbox // (its PID namespace's init and all below it, read from the host's // /proc) every memoryEvery, and calls over once, when the sum is above // limit. The returned stop ends the watch and waits for it. func watchMemory(s *Sandbox, limit int64, over func()) (stop func()) { done := make(chan struct{}) // The init is known once Launch returns; read once, its number // cannot name another process while the sandbox runs. pid := s.initPID() var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() tick := time.NewTicker(memoryEvery) defer tick.Stop() for { if pid > 0 && treeRSS(pid) > limit { over() return } select { case <-done: return case <-s.done: return case <-tick.C: } } }() var once sync.Once return func() { once.Do(func() { close(done) }) wg.Wait() } } // initPID is the sandbox's PID namespace init, from its pidfd, or 0. func (s *Sandbox) initPID() int { s.mu.Lock() fd := s.pidfd s.mu.Unlock() if fd < 0 { return 0 } raw, err := os.ReadFile(fmt.Sprintf("/proc/self/fdinfo/%d", fd)) if err != nil { return 0 } for _, line := range strings.Split(string(raw), "\n") { if v, ok := strings.CutPrefix(line, "Pid:"); ok { n, _ := strconv.Atoi(strings.TrimSpace(v)) return max(n, 0) } } return 0 } // maxProcs bounds the processes one sum reads. const maxProcs = 1 << 16 // treeRSS is the resident memory, in bytes, of root and every process // below it. Shared pages count once a process, so the sum is never less // than what the processes hold. func treeRSS(root int) int64 { children := map[int][]int{} dir, err := os.Open("/proc") if err != nil { return 0 } names, _ := dir.Readdirnames(maxProcs) dir.Close() for _, name := range names { pid, err := strconv.Atoi(name) if err != nil || pid <= 0 { continue } if ppid := parentFromStat(pid); ppid > 0 { children[ppid] = append(children[ppid], pid) } } page := int64(os.Getpagesize()) var sum int64 seen := map[int]bool{} queue := []int{root} for len(queue) > 0 && len(seen) < maxProcs { pid := queue[0] queue = queue[1:] if seen[pid] { continue } seen[pid] = true sum += residentPages(pid) * page queue = append(queue, children[pid]...) } return sum } // parentFromStat is pid's parent from /proc//stat, or 0. The // command name, in parentheses, may hold anything: the fields after its // last ")" are the kernel's. func parentFromStat(pid int) int { raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat") if err != nil { return 0 } i := bytes.LastIndexByte(raw, ')') if i < 0 { return 0 } fields := strings.Fields(string(raw[i+1:])) if len(fields) < 2 { return 0 } n, _ := strconv.Atoi(fields[1]) return n } // residentPages is pid's resident set in pages, from /proc//statm. func residentPages(pid int) int64 { raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/statm") if err != nil { return 0 } fields := strings.Fields(string(raw)) if len(fields) < 2 { return 0 } n, _ := strconv.ParseInt(fields[1], 10, 64) return max(n, 0) }