1// Copyright 2017 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package main
6
7import (
8	"bytes"
9	"fmt"
10	"io/ioutil"
11	"os"
12	"syscall"
13)
14
15func gettid() int {
16	return syscall.Gettid()
17}
18
19func tidExists(tid int) (exists, supported bool) {
20	stat, err := ioutil.ReadFile(fmt.Sprintf("/proc/self/task/%d/stat", tid))
21	if os.IsNotExist(err) {
22		return false, true
23	}
24	// Check if it's a zombie thread.
25	state := bytes.Fields(stat)[2]
26	return !(len(state) == 1 && state[0] == 'Z'), true
27}
28
29func getcwd() (string, error) {
30	if !syscall.ImplementsGetwd {
31		return "", nil
32	}
33	// Use the syscall to get the current working directory.
34	// This is imperative for checking for OS thread state
35	// after an unshare since os.Getwd might just check the
36	// environment, or use some other mechanism.
37	var buf [4096]byte
38	n, err := syscall.Getcwd(buf[:])
39	if err != nil {
40		return "", err
41	}
42	// Subtract one for null terminator.
43	return string(buf[:n-1]), nil
44}
45
46func unshareFs() error {
47	err := syscall.Unshare(syscall.CLONE_FS)
48	if err != nil {
49		errno, ok := err.(syscall.Errno)
50		if ok && errno == syscall.EPERM {
51			return errNotPermitted
52		}
53	}
54	return err
55}
56
57func chdir(path string) error {
58	return syscall.Chdir(path)
59}
60