// BPF programs and sockmaps working on cgroups
335136
func bpftoolMapAttach(progID string, mapID string) error {
	prog := "bpftool"

	args := []string{"prog", "attach", "id", progID, "msg_verdict", "id", mapID}
	log.WithFields(logrus.Fields{
		"bpftool": prog,
		"args":    args,
	}).Debug("Map Attach BPF Object:")
	out, err := exec.Command(prog, args...).CombinedOutput()
	if err != nil {
		return fmt.Errorf("Failed to attach prog(%s) to map(%s): %s: %s", progID, mapID, err, out)
	}
	return nil
}
1218123
func GetBoostrapSCCAccess(infraNamespace string) (map[string][]string, map[string][]string) {
	groups := map[string][]string{
		SecurityContextConstraintPrivileged: {ClusterAdminGroup, NodesGroup, MastersGroup},
		SecurityContextConstraintsAnyUID:    {ClusterAdminGroup},
		SecurityContextConstraintRestricted: {AuthenticatedGroup},
	}

	buildControllerUsername := serviceaccount.MakeUsername(infraNamespace, InfraBuildControllerServiceAccountName)
	pvRecyclerControllerUsername := serviceaccount.MakeUsername(infraNamespace, InfraPersistentVolumeRecyclerControllerServiceAccountName)
	users := map[string][]string{
		SecurityContextConstraintPrivileged:         {SystemAdminUsername, buildControllerUsername},
		SecurityContextConstraintHostMountAndAnyUID: {pvRecyclerControllerUsername},
	}
	return groups, users
}
1137046
func (m *Matrix) BroadcastFunc(f func(float32, ...interface{}) float32, args ...interface{}) *Matrix {
	newMatrix := make([][]float32, m.Rows)
	var wg sync.WaitGroup
	for y := 0; y < int(m.Rows); y++ {
		wg.Add(1)
		go m.execFunc(newMatrix, y, &wg, f, args...)
	}
	wg.Wait()
	return NewMatrix(newMatrix)
}
962934
func SerializePairs(pairs map[string]string) string {
	tmp := make([]string, 0, len(pairs))

	for k, v := range pairs {
		tmp = append(tmp, fmt.Sprintf("%s=%s", k, v))
	}
	return strings.Join(tmp, ",")
}
713551
func (m *cgroupManagerImpl) Pids(name CgroupName) []int {
	// we need the driver specific name
	cgroupFsName := m.Name(name)

	// Get a list of processes that we need to kill
	pidsToKill := sets.NewInt()
	var pids []int
	for _, val := range m.subsystems.MountPoints {
		dir := path.Join(val, cgroupFsName)
		_, err := os.Stat(dir)
		if os.IsNotExist(err) {
			// The subsystem pod cgroup is already deleted
			// do nothing, continue
			continue
		}
		// Get a list of pids that are still charged to the pod's cgroup
		pids, err = getCgroupProcs(dir)
		if err != nil {
			continue
		}
		pidsToKill.Insert(pids...)

		// WalkFunc which is called for each file and directory in the pod cgroup dir
		visitor := func(path string, info os.FileInfo, err error) error {
			if err != nil {
				klog.V(4).Infof("cgroup manager encountered error scanning cgroup path %q: %v", path, err)
				return filepath.SkipDir
			}
			if !info.IsDir() {
				return nil
			}
			pids, err = getCgroupProcs(path)
			if err != nil {
				klog.V(4).Infof("cgroup manager encountered error getting procs for cgroup path %q: %v", path, err)
				return filepath.SkipDir
			}
			pidsToKill.Insert(pids...)
			return nil
		}
		// Walk through the pod cgroup directory to check if
		// container cgroups haven't been GCed yet. Get attached processes to
		// all such unwanted containers under the pod cgroup
		if err = filepath.Walk(dir, visitor); err != nil {
			klog.V(4).Infof("cgroup manager encountered error scanning pids for directory: %q: %v", dir, err)
		}
	}
	return pidsToKill.List()
}
220489
func (c *Conn) ObjectGroups(attr, value string, groups []string) ([]string, error) {
	entry, err := c.GetAttributes(attr, value, []string{"memberOf"})
	if err != nil {
		return nil, err
	}
	var objectGroups []string

	for _, objectGroup := range entry.GetAttributeValues("memberOf") {
		for _, parentGroup := range groups {
			if objectGroup == parentGroup {
				objectGroups = append(objectGroups, parentGroup)
				continue
			}
		}
	}

	return objectGroups, nil
}
611332
func (g *Group) BlockFunc(f func(*Group)) *Statement {
	s := BlockFunc(f)
	g.items = append(g.items, s)
	return s
}
1012936
func (inst *DenseInstances) AllAttributeGroups() map[string]AttributeGroup {
	ret := make(map[string]AttributeGroup)
	for a := range inst.agMap {
		ret[a] = inst.ags[inst.agMap[a]]
	}
	return ret
}
1289478
func (tc *TransCache) GetGroupItems(chID, grpID string) (itms []interface{}) {
	tc.cacheMux.RLock()
	itms = tc.cacheInstance(chID).GetGroupItems(grpID)
	tc.cacheMux.RUnlock()
	return
}
1372080
func (m *MockCgroupnetcls) ListCgroupProcesses(cgroupname string) ([]string, error) {
	ret := m.ctrl.Call(m, "ListCgroupProcesses", cgroupname)
	ret0, _ := ret[0].([]string)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
15449
func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value {
	groups := make(map[string][](Map))
	v.EachObjxMap(func(index int, val Map) bool {
		group := grouper(index, val)
		if _, ok := groups[group]; !ok {
			groups[group] = make([](Map), 0)
		}
		groups[group] = append(groups[group], val)
		return true
	})
	return &Value{data: groups}
}
523131
func TypeGroupsByBucket(bucket TypeBucket) []WorkItemTypeGroup {
	res := []WorkItemTypeGroup{}
	for _, t := range TypeGroups() {
		if t.Bucket == bucket {
			res = append(res, t)
		}
	}
	return res
}
917307
func CheckOrMountFS(bpfRoot string) {
	mountOnce.Do(func() {
		if err := checkOrMountFS(bpfRoot); err != nil {
			log.WithError(err).Fatal("Unable to mount BPF filesystem")
		}
	})
}
1125629
func typecheck(ctx context.Context, fset *token.FileSet, bctx *build.Context, bpkg *build.Package, findPackage FindPackageFunc, rootPath string) (*loader.Program, diagnostics, error) {
	var typeErrs []error
	conf := loader.Config{
		Fset: fset,
		TypeChecker: types.Config{
			DisableUnusedImportCheck: true,
			FakeImportC:              true,
			Error: func(err error) {
				typeErrs = append(typeErrs, err)
			},
		},
		Build:       bctx,
		Cwd:         bpkg.Dir,
		AllowErrors: true,
		TypeCheckFuncBodies: func(p string) bool {
			return bpkg.ImportPath == p
		},
		ParserMode: parser.AllErrors | parser.ParseComments, // prevent parser from bailing out
		FindPackage: func(bctx *build.Context, importPath, fromDir string, mode build.ImportMode) (*build.Package, error) {
			// When importing a package, ignore any
			// MultipleGoErrors. This occurs, e.g., when you have a
			// main.go with "// +build ignore" that imports the
			// non-main package in the same dir.
			bpkg, err := findPackage(ctx, bctx, importPath, fromDir, rootPath, mode)
			if err != nil && !isMultiplePackageError(err) {
				return bpkg, err
			}
			return bpkg, nil
		},
	}

	// Hover needs this info, otherwise we could zero out the unnecessary
	// results to save memory.
	//
	// TODO(sqs): investigate other ways to speed this up using
	// AfterTypeCheck; see
	// https://sourcegraph.com/github.com/golang/tools@5ffc3249d341c947aa65178abbf2253ed49c9e03/-/blob/cmd/guru/referrers.go#L148.
	//
	// 	conf.AfterTypeCheck = func(info *loader.PackageInfo, files []*ast.File) {
	// 		if !conf.TypeCheckFuncBodies(info.Pkg.Path()) {
	// 			clearInfoFields(info)
	// 		}
	// 	}
	//

	var goFiles []string
	goFiles = append(goFiles, bpkg.GoFiles...)
	goFiles = append(goFiles, bpkg.TestGoFiles...)
	if strings.HasSuffix(bpkg.Name, "_test") {
		goFiles = append(goFiles, bpkg.XTestGoFiles...)
	}
	for i, filename := range goFiles {
		goFiles[i] = buildutil.JoinPath(bctx, bpkg.Dir, filename)
	}
	conf.CreateFromFilenames(bpkg.ImportPath, goFiles...)
	prog, err := conf.Load()
	if err != nil && prog == nil {
		return nil, nil, err
	}
	diags, err := errsToDiagnostics(typeErrs, prog)
	if err != nil {
		return nil, nil, err
	}
	return prog, diags, nil
}
1181648
func (p *packetConn) SetBPF(filter []bpf.RawInstruction) error {
	// Base filter filters traffic based on EtherType
	base, err := bpf.Assemble(baseFilter(p.proto))
	if err != nil {
		return err
	}

	// Append user filter to base filter, translate to raw format,
	// and apply to BPF device
	return syscall.SetBpf(p.fd, assembleBpfInsn(append(base, filter...)))
}
1161539
func loadSimpleBpf(progType BpfProgType, ret uint32) (int, error) {
	insns := []uint64{
		0x00000000000000b7 | (uint64(ret) << 32),
		0x0000000000000095,
	}
	license := []byte{'A', 'S', 'L', '2', '\x00'}
	attr := BPFAttr{
		ProgType: uint32(progType),
		InsnCnt:  uint32(len(insns)),
		Insns:    uintptr(unsafe.Pointer(&insns[0])),
		License:  uintptr(unsafe.Pointer(&license[0])),
	}
	fd, _, errno := unix.Syscall(unix.SYS_BPF,
		5, /* bpf cmd */
		uintptr(unsafe.Pointer(&attr)),
		unsafe.Sizeof(attr))
	if errno != 0 {
		return 0, errno
	}
	return int(fd), nil
}
508411
func (s *netCls) ListAllCgroups(path string) []string {

	cgroups, err := ioutil.ReadDir(filepath.Join(basePath, s.TriremePath, path))
	if err != nil {
		return []string{}
	}

	names := make([]string, len(cgroups))
	for i := 0; i < len(cgroups); i++ {
		names[i] = cgroups[i].Name()
	}

	return names
}