github.com/anonymouse64/snapd@v0.0.0-20210824153203-04c4c42d842d/osutil/sys_linux.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2018 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package osutil
    21  
    22  import (
    23  	"syscall"
    24  	"unsafe"
    25  )
    26  
    27  // Symlinkat is a direct pass-through to the symlinkat(2) system call.
    28  func Symlinkat(target string, dirfd int, linkpath string) error {
    29  	targetPtr, err := syscall.BytePtrFromString(target)
    30  	if err != nil {
    31  		return err
    32  	}
    33  	linkpathPtr, err := syscall.BytePtrFromString(linkpath)
    34  	if err != nil {
    35  		return err
    36  	}
    37  	_, _, errno := syscall.Syscall(syscall.SYS_SYMLINKAT, uintptr(unsafe.Pointer(targetPtr)), uintptr(dirfd), uintptr(unsafe.Pointer(linkpathPtr)))
    38  	if errno != 0 {
    39  		return errno
    40  	}
    41  	return nil
    42  }
    43  
    44  // Readlinkat is a direct pass-through to the readlinkat(2) system call.
    45  func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) {
    46  	var zero uintptr
    47  
    48  	pathPtr, err := syscall.BytePtrFromString(path)
    49  	if err != nil {
    50  		return 0, err
    51  	}
    52  	var bufPtr unsafe.Pointer
    53  	if len(buf) > 0 {
    54  		bufPtr = unsafe.Pointer(&buf[0])
    55  	} else {
    56  		bufPtr = unsafe.Pointer(&zero)
    57  	}
    58  	r0, _, errno := syscall.Syscall6(syscall.SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(pathPtr)), uintptr(bufPtr), uintptr(len(buf)), 0, 0)
    59  	n = int(r0)
    60  	if errno != 0 {
    61  		return 0, errno
    62  	}
    63  	return n, nil
    64  }