github.com/camlistore/go4@v0.0.0-20200104003542-c7e774b10ea0/osutil/exec_sysctl.go (about)

     1  // Copyright 2015 The go4 Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // +build freebsd darwin
    16  
    17  package osutil
    18  
    19  import (
    20  	"os"
    21  	"path/filepath"
    22  	"runtime"
    23  	"syscall"
    24  	"unsafe"
    25  )
    26  
    27  var cacheWD, cacheWDErr = os.Getwd()
    28  
    29  func executable() (string, error) {
    30  	var mib [4]int32
    31  	switch runtime.GOOS {
    32  	case "freebsd":
    33  		mib = [4]int32{1 /* CTL_KERN */, 14 /* KERN_PROC */, 12 /* KERN_PROC_PATHNAME */, -1}
    34  	case "darwin":
    35  		mib = [4]int32{1 /* CTL_KERN */, 38 /* KERN_PROCARGS */, int32(os.Getpid()), -1}
    36  	}
    37  
    38  	n := uintptr(0)
    39  	// get length
    40  	_, _, err := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, 0, uintptr(unsafe.Pointer(&n)), 0, 0)
    41  	if err != 0 {
    42  		return "", err
    43  	}
    44  	if n == 0 { // shouldn't happen
    45  		return "", nil
    46  	}
    47  	buf := make([]byte, n)
    48  	_, _, err = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n)), 0, 0)
    49  	if err != 0 {
    50  		return "", err
    51  	}
    52  	if n == 0 { // shouldn't happen
    53  		return "", nil
    54  	}
    55  	p := string(buf[:n-1])
    56  	if !filepath.IsAbs(p) {
    57  		if cacheWDErr != nil {
    58  			return p, cacheWDErr
    59  		}
    60  		p = filepath.Join(cacheWD, filepath.Clean(p))
    61  	}
    62  	return filepath.EvalSymlinks(p)
    63  }