github.com/MerlinKodo/gvisor@v0.0.0-20231110090155-957f62ecf90e/pkg/sentry/strace/select.go (about)

     1  // Copyright 2019 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 strace
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"github.com/MerlinKodo/gvisor/pkg/sentry/kernel"
    21  	"github.com/MerlinKodo/gvisor/pkg/sentry/syscalls/linux"
    22  
    23  	"github.com/MerlinKodo/gvisor/pkg/hostarch"
    24  )
    25  
    26  func fdsFromSet(t *kernel.Task, set []byte) []int {
    27  	var fds []int
    28  	// Append n if the n-th bit is 1.
    29  	for i, v := range set {
    30  		for j := 0; j < 8; j++ {
    31  			if (v>>j)&1 == 1 {
    32  				fds = append(fds, i*8+j)
    33  			}
    34  		}
    35  	}
    36  	return fds
    37  }
    38  
    39  func fdSet(t *kernel.Task, nfds int, addr hostarch.Addr) string {
    40  	if nfds < 0 {
    41  		return fmt.Sprintf("%#x (negative nfds)", addr)
    42  	}
    43  	if addr == 0 {
    44  		return "null"
    45  	}
    46  
    47  	// Calculate the size of the fd set (one bit per fd).
    48  	nBytes := (nfds + 7) / 8
    49  	nBitsInLastPartialByte := nfds % 8
    50  
    51  	set, err := linux.CopyInFDSet(t, addr, nBytes, nBitsInLastPartialByte)
    52  	if err != nil {
    53  		return fmt.Sprintf("%#x (error decoding fdset: %s)", addr, err)
    54  	}
    55  
    56  	return fmt.Sprintf("%#x %v", addr, fdsFromSet(t, set))
    57  }