github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/fs/host/descriptor_test.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 host
    16  
    17  import (
    18  	"io/ioutil"
    19  	"path/filepath"
    20  	"testing"
    21  
    22  	"golang.org/x/sys/unix"
    23  	"github.com/SagerNet/gvisor/pkg/fdnotifier"
    24  	"github.com/SagerNet/gvisor/pkg/waiter"
    25  )
    26  
    27  func TestDescriptorRelease(t *testing.T) {
    28  	for _, tc := range []struct {
    29  		name       string
    30  		saveable   bool
    31  		wouldBlock bool
    32  	}{
    33  		{name: "all false"},
    34  		{name: "saveable", saveable: true},
    35  		{name: "wouldBlock", wouldBlock: true},
    36  	} {
    37  		t.Run(tc.name, func(t *testing.T) {
    38  			dir, err := ioutil.TempDir("", "descriptor_test")
    39  			if err != nil {
    40  				t.Fatal("ioutil.TempDir() failed:", err)
    41  			}
    42  
    43  			fd, err := unix.Open(filepath.Join(dir, "file"), unix.O_RDWR|unix.O_CREAT, 0666)
    44  			if err != nil {
    45  				t.Fatal("failed to open temp file:", err)
    46  			}
    47  
    48  			// FD ownership is transferred to the descritor.
    49  			queue := &waiter.Queue{}
    50  			d, err := newDescriptor(fd, tc.saveable, tc.wouldBlock, queue)
    51  			if err != nil {
    52  				unix.Close(fd)
    53  				t.Fatalf("newDescriptor(%d, %t, %t, queue) failed, err: %v", fd, tc.saveable, tc.wouldBlock, err)
    54  			}
    55  			if tc.saveable {
    56  				if d.origFD < 0 {
    57  					t.Errorf("saveable descriptor must preserve origFD, desc: %+v", d)
    58  				}
    59  			}
    60  			if tc.wouldBlock {
    61  				if !fdnotifier.HasFD(int32(d.value)) {
    62  					t.Errorf("FD not registered with notifier, desc: %+v", d)
    63  				}
    64  			}
    65  
    66  			oldVal := d.value
    67  			d.Release()
    68  			if d.value != -1 {
    69  				t.Errorf("d.value want: -1, got: %d", d.value)
    70  			}
    71  			if tc.wouldBlock {
    72  				if fdnotifier.HasFD(int32(oldVal)) {
    73  					t.Errorf("FD not unregistered with notifier, desc: %+v", d)
    74  				}
    75  			}
    76  		})
    77  	}
    78  }