github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/pkg/subsystem/service.go (about)

     1  // Copyright 2023 syzkaller project authors. All rights reserved.
     2  // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
     3  
     4  package subsystem
     5  
     6  import (
     7  	"fmt"
     8  )
     9  
    10  type Service struct {
    11  	*Extractor
    12  	perName   map[string]*Subsystem
    13  	perParent map[*Subsystem][]*Subsystem
    14  }
    15  
    16  func MustMakeService(list []*Subsystem) *Service {
    17  	if len(list) == 0 {
    18  		panic("the subsystem list is empty")
    19  	}
    20  	service, err := MakeService(list)
    21  	if err != nil {
    22  		panic(fmt.Sprintf("service creation failed: %s", err))
    23  	}
    24  	return service
    25  }
    26  
    27  func MakeService(list []*Subsystem) (*Service, error) {
    28  	extractor := MakeExtractor(list)
    29  	perName := map[string]*Subsystem{}
    30  	perParent := map[*Subsystem][]*Subsystem{}
    31  	for _, item := range list {
    32  		if item.Name == "" {
    33  			return nil, fmt.Errorf("input contains a subsystem without a name")
    34  		}
    35  		if perName[item.Name] != nil {
    36  			return nil, fmt.Errorf("collision on %#v name", item.Name)
    37  		}
    38  		perName[item.Name] = item
    39  		for _, p := range item.Parents {
    40  			perParent[p] = append(perParent[p], item)
    41  		}
    42  	}
    43  	return &Service{
    44  		Extractor: extractor,
    45  		perName:   perName,
    46  		perParent: perParent,
    47  	}, nil
    48  }
    49  
    50  func (s *Service) ByName(name string) *Subsystem {
    51  	return s.perName[name]
    52  }
    53  
    54  func (s *Service) List() []*Subsystem {
    55  	ret := []*Subsystem{}
    56  	for _, item := range s.perName {
    57  		ret = append(ret, item)
    58  	}
    59  	return ret
    60  }
    61  
    62  func (s *Service) Children(parent *Subsystem) []*Subsystem {
    63  	return append([]*Subsystem{}, s.perParent[parent]...)
    64  }