github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/syscalls/linux/vfs2/eventfd.go (about)

     1  // Copyright 2018 The gVisor 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  package vfs2
    16  
    17  import (
    18  	"github.com/SagerNet/gvisor/pkg/abi/linux"
    19  	"github.com/SagerNet/gvisor/pkg/errors/linuxerr"
    20  	"github.com/SagerNet/gvisor/pkg/sentry/arch"
    21  	"github.com/SagerNet/gvisor/pkg/sentry/fsimpl/eventfd"
    22  	"github.com/SagerNet/gvisor/pkg/sentry/kernel"
    23  )
    24  
    25  // Eventfd2 implements linux syscall eventfd2(2).
    26  func Eventfd2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
    27  	initVal := uint64(args[0].Uint())
    28  	flags := uint(args[1].Uint())
    29  	allOps := uint(linux.EFD_SEMAPHORE | linux.EFD_NONBLOCK | linux.EFD_CLOEXEC)
    30  
    31  	if flags & ^allOps != 0 {
    32  		return 0, nil, linuxerr.EINVAL
    33  	}
    34  
    35  	vfsObj := t.Kernel().VFS()
    36  	fileFlags := uint32(linux.O_RDWR)
    37  	if flags&linux.EFD_NONBLOCK != 0 {
    38  		fileFlags |= linux.O_NONBLOCK
    39  	}
    40  	semMode := flags&linux.EFD_SEMAPHORE != 0
    41  	eventfd, err := eventfd.New(t, vfsObj, initVal, semMode, fileFlags)
    42  	if err != nil {
    43  		return 0, nil, err
    44  	}
    45  	defer eventfd.DecRef(t)
    46  
    47  	fd, err := t.NewFDFromVFS2(0, eventfd, kernel.FDFlags{
    48  		CloseOnExec: flags&linux.EFD_CLOEXEC != 0,
    49  	})
    50  	if err != nil {
    51  		return 0, nil, err
    52  	}
    53  
    54  	return uintptr(fd), nil, nil
    55  }
    56  
    57  // Eventfd implements linux syscall eventfd(2).
    58  func Eventfd(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
    59  	args[1].Value = 0
    60  	return Eventfd2(t, args)
    61  }