gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/cpuid/cpuid_parse_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 cpuid
    16  
    17  import (
    18  	"io/ioutil"
    19  	"os"
    20  	"regexp"
    21  	"strings"
    22  	"testing"
    23  
    24  	"gvisor.dev/gvisor/pkg/hostos"
    25  )
    26  
    27  // TestHostFeatureFlags tests that all features detected by HostFeatureSet are
    28  // on the host.
    29  //
    30  // It does *not* verify that all features reported by the host are detected by
    31  // HostFeatureSet. Linux has synthetic Linux-specific features that have no
    32  // analog in the actual CPUID feature set.
    33  func TestHostFeatureFlags(t *testing.T) {
    34  	// Extract the kernel version.
    35  	version, err := hostos.KernelVersion()
    36  	if err != nil {
    37  		t.Fatalf("Unable to parse kernel version: %v", err)
    38  	}
    39  
    40  	// Extract all cpuinfo flags.
    41  	cpuinfoBytes, _ := ioutil.ReadFile("/proc/cpuinfo")
    42  	cpuinfo := string(cpuinfoBytes)
    43  	re := regexp.MustCompile(`(?m)^flags\s+: (.*)$`)
    44  	m := re.FindStringSubmatch(cpuinfo)
    45  	if len(m) != 2 {
    46  		t.Fatalf("Unable to extract flags from %q", cpuinfo)
    47  	}
    48  	cpuinfoFlags := make(map[string]struct{})
    49  	for _, f := range strings.Split(m[1], " ") {
    50  		cpuinfoFlags[f] = struct{}{}
    51  	}
    52  
    53  	// Check against host flags.
    54  	fs := HostFeatureSet()
    55  	for feature, info := range allFeatures {
    56  		// Special cases not consistently visible. We don't mind if
    57  		// they are exposed in earlier versions.
    58  		if archSkipFeature(feature, version) {
    59  			continue
    60  		}
    61  
    62  		// Check against the flags.
    63  		_, ok := cpuinfoFlags[feature.String()]
    64  		if !info.shouldAppear && ok {
    65  			t.Errorf("Unexpected flag: %v", feature)
    66  		} else if info.shouldAppear && fs.HasFeature(feature) && !ok {
    67  			t.Errorf("Missing flag: %v", feature)
    68  		}
    69  	}
    70  }
    71  
    72  func TestMain(m *testing.M) {
    73  	Initialize()
    74  	os.Exit(m.Run())
    75  }