github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/kernel/eventfd/eventfd_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 eventfd
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/SagerNet/gvisor/pkg/sentry/contexttest"
    21  	"github.com/SagerNet/gvisor/pkg/usermem"
    22  	"github.com/SagerNet/gvisor/pkg/waiter"
    23  )
    24  
    25  func TestEventfd(t *testing.T) {
    26  	initVals := []uint64{
    27  		0,
    28  		// Using a non-zero initial value verifies that writing to an
    29  		// eventfd signals when the eventfd's counter was already
    30  		// non-zero.
    31  		343,
    32  	}
    33  
    34  	for _, initVal := range initVals {
    35  		ctx := contexttest.Context(t)
    36  
    37  		// Make a new event that is writable.
    38  		event := New(ctx, initVal, false)
    39  
    40  		// Register a callback for a write event.
    41  		w, ch := waiter.NewChannelEntry(nil)
    42  		event.EventRegister(&w, waiter.ReadableEvents)
    43  		defer event.EventUnregister(&w)
    44  
    45  		data := []byte("00000124")
    46  		// Create and submit a write request.
    47  		n, err := event.Writev(ctx, usermem.BytesIOSequence(data))
    48  		if err != nil {
    49  			t.Fatal(err)
    50  		}
    51  		if n != 8 {
    52  			t.Errorf("eventfd.write wrote %d bytes, not full int64", n)
    53  		}
    54  
    55  		// Check if the callback fired due to the write event.
    56  		select {
    57  		case <-ch:
    58  		default:
    59  			t.Errorf("Didn't get notified of EventIn after write")
    60  		}
    61  	}
    62  }
    63  
    64  func TestEventfdStat(t *testing.T) {
    65  	ctx := contexttest.Context(t)
    66  
    67  	// Make a new event that is writable.
    68  	event := New(ctx, 0, false)
    69  
    70  	// Create and submit an stat request.
    71  	uattr, err := event.Dirent.Inode.UnstableAttr(ctx)
    72  	if err != nil {
    73  		t.Fatalf("eventfd stat request failed: %v", err)
    74  	}
    75  	if uattr.Size != 0 {
    76  		t.Fatal("EventFD size should be 0")
    77  	}
    78  }