github.com/nicocha30/gvisor-ligolo@v0.0.0-20230726075806-989fa2c0a413/pkg/abi/flag.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 abi 16 17 import ( 18 "fmt" 19 "math" 20 "strconv" 21 "strings" 22 ) 23 24 // A FlagSet is a slice of bit-flags and their name. 25 type FlagSet []struct { 26 Flag uint64 27 Name string 28 } 29 30 // Parse returns a pretty version of val, using the flag names for known flags. 31 // Unknown flags remain numeric. 32 func (s FlagSet) Parse(val uint64) string { 33 var flags []string 34 35 for _, f := range s { 36 if val&f.Flag == f.Flag { 37 flags = append(flags, f.Name) 38 val &^= f.Flag 39 } 40 } 41 42 if val != 0 { 43 flags = append(flags, "0x"+strconv.FormatUint(val, 16)) 44 } 45 46 if len(flags) == 0 { 47 // Prefer 0 to an empty string. 48 return "0x0" 49 } 50 51 return strings.Join(flags, "|") 52 } 53 54 // ValueSet is a map of syscall values to their name. Parse will use the name 55 // or the value if unknown. 56 type ValueSet map[uint64]string 57 58 // Parse returns the name of the value associated with `val`. Unknown values 59 // are converted to hex. 60 func (s ValueSet) Parse(val uint64) string { 61 if v, ok := s[val]; ok { 62 return v 63 } 64 return fmt.Sprintf("%#x", val) 65 } 66 67 // ParseDecimal returns the name of the value associated with `val`. Unknown 68 // values are converted to decimal. 69 func (s ValueSet) ParseDecimal(val uint64) string { 70 if v, ok := s[val]; ok { 71 return v 72 } 73 return fmt.Sprintf("%d", val) 74 } 75 76 // ParseName returns the flag value associated with 'name'. Returns false 77 // if no value is found. 78 func (s ValueSet) ParseName(name string) (uint64, bool) { 79 for k, v := range s { 80 if v == name { 81 return k, true 82 } 83 } 84 return math.MaxUint64, false 85 }