// parseOptions parses fstab type mount options into mount() flags
// and device specific data
167928
func parseOptions(options string) (int, string) {
	var (
		flag int
		data []string
	)

	flags := map[string]struct {
		clear bool
		flag  int
	}{
		"defaults":      {false, 0},
		"ro":            {false, RDONLY},
		"rw":            {true, RDONLY},
		"suid":          {true, NOSUID},
		"nosuid":        {false, NOSUID},
		"dev":           {true, NODEV},
		"nodev":         {false, NODEV},
		"exec":          {true, NOEXEC},
		"noexec":        {false, NOEXEC},
		"sync":          {false, SYNCHRONOUS},
		"async":         {true, SYNCHRONOUS},
		"dirsync":       {false, DIRSYNC},
		"remount":       {false, REMOUNT},
		"mand":          {false, MANDLOCK},
		"nomand":        {true, MANDLOCK},
		"atime":         {true, NOATIME},
		"noatime":       {false, NOATIME},
		"diratime":      {true, NODIRATIME},
		"nodiratime":    {false, NODIRATIME},
		"bind":          {false, BIND},
		"rbind":         {false, RBIND},
		"unbindable":    {false, UNBINDABLE},
		"runbindable":   {false, RUNBINDABLE},
		"private":       {false, PRIVATE},
		"rprivate":      {false, RPRIVATE},
		"shared":        {false, SHARED},
		"rshared":       {false, RSHARED},
		"slave":         {false, SLAVE},
		"rslave":        {false, RSLAVE},
		"relatime":      {false, RELATIME},
		"norelatime":    {true, RELATIME},
		"strictatime":   {false, STRICTATIME},
		"nostrictatime": {true, STRICTATIME},
	}

	for _, o := range strings.Split(options, ",") {
		// If the option does not exist in the flags table or the flag
		// is not supported on the platform,
		// then it is a data value for a specific fs type
		if f, exists := flags[o]; exists && f.flag != 0 {
			if f.clear {
				flag &= ^f.flag
			} else {
				flag |= f.flag
			}
		} else {
			data = append(data, o)
		}
	}
	return flag, strings.Join(data, ",")
}
430960
func ParseMounts(pid uint) (Mounts, error) {
	var procPath string
	if pid == 0 {
		procPath = "/proc/self/mountinfo"
	} else {
		procPath = fmt.Sprintf("/proc/%d/mountinfo", pid)
	}

	mi, err := os.Open(procPath)
	if err != nil {
		return nil, err
	}
	defer mi.Close()

	return parseMountinfo(mi)
}
645747
func LoadOptions(filename string) (*Options, error) {
	var bs []byte
	if strings.HasPrefix(filename, "{") {
		bs = []byte(filename)
	} else {
		var err error
		log.Printf("LoadOptions reading %s", filename)
		bs, err = ioutil.ReadFile(filename)
		if err != nil {
			log.Printf("LoadOptions error: %v (%s)", err, filename)
			return nil, err
		}
	}

	opts := make(Options)
	err := json.Unmarshal(bs, &opts)
	if err != nil {
		log.Printf("LoadOptions unmarshal error: %v on \"%s\"", err, bs)
		return nil, err
	}

	return &opts, nil
}
446779
func parseMountTable(filter FilterFunc) ([]*Info, error) {
	f, err := os.Open("/proc/self/mountinfo")
	if err != nil {
		return nil, err
	}
	defer f.Close()

	return parseInfoFile(f, filter)
}
1185305
func (p *parser) popOptions() {
	lastIdx := len(p.optionsStack) - 1
	// get the last item on the stack and then remove it by reslicing
	p.options = p.optionsStack[lastIdx]
	p.optionsStack = p.optionsStack[:lastIdx]
}
277349
func parseTmpfsOptions(options string) (int, string, error) {
	flags, data := parseOptions(options)
	validFlags := map[string]bool{
		"":          true,
		"size":      true,
		"mode":      true,
		"uid":       true,
		"gid":       true,
		"nr_inodes": true,
		"nr_blocks": true,
		"mpol":      true,
	}
	for _, o := range strings.Split(data, ",") {
		opt := strings.SplitN(o, "=", 2)
		if !validFlags[opt[0]] {
			return 0, "", fmt.Errorf("Invalid tmpfs option %q", opt)
		}
	}
	return flags, data, nil
}
1243673
func (c *agentConfig) parseCmdlineOption(option string) error {
	const (
		optionPosition = iota
		valuePosition
		optionSeparator = "="
	)

	if option == devModeFlag {
		crashOnError = true
		debug = true

		return nil
	}

	if option == traceModeFlag {
		enableTracing(traceModeStatic, defaultTraceType)
		return nil
	}

	split := strings.Split(option, optionSeparator)

	if len(split) < valuePosition+1 {
		return nil
	}

	switch split[optionPosition] {
	case logLevelFlag:
		level, err := logrus.ParseLevel(split[valuePosition])
		if err != nil {
			return err
		}
		c.logLevel = level
		if level == logrus.DebugLevel {
			debug = true
		}
	case traceModeFlag:
		switch split[valuePosition] {
		case traceTypeIsolated:
			enableTracing(traceModeStatic, traceTypeIsolated)
		case traceTypeCollated:
			enableTracing(traceModeStatic, traceTypeCollated)
		}
	case useVsockFlag:
		flag, err := strconv.ParseBool(split[valuePosition])
		if err != nil {
			return err
		}
		if flag {
			agentLog.Debug("Param passed to use vsock channel")
			commCh = vsockCh
		} else {
			agentLog.Debug("Param passed to NOT use vsock channel")
			commCh = serialCh
		}
	default:
		if strings.HasPrefix(split[optionPosition], optionPrefix) {
			return grpcStatus.Errorf(codes.NotFound, "Unknown option %s", split[optionPosition])
		}
	}

	return nil

}
1210786
func parseFlags(o *plugin.Options) (*source, []string, error) {
	flag := o.Flagset
	// Comparisons.
	flagDiffBase := flag.StringList("diff_base", "", "Source of base profile for comparison")
	flagBase := flag.StringList("base", "", "Source of base profile for profile subtraction")
	// Source options.
	flagSymbolize := flag.String("symbolize", "", "Options for profile symbolization")
	flagBuildID := flag.String("buildid", "", "Override build id for first mapping")
	flagTimeout := flag.Int("timeout", -1, "Timeout in seconds for fetching a profile")
	flagAddComment := flag.String("add_comment", "", "Annotation string to record in the profile")
	// CPU profile options
	flagSeconds := flag.Int("seconds", -1, "Length of time for dynamic profiles")
	// Heap profile options
	flagInUseSpace := flag.Bool("inuse_space", false, "Display in-use memory size")
	flagInUseObjects := flag.Bool("inuse_objects", false, "Display in-use object counts")
	flagAllocSpace := flag.Bool("alloc_space", false, "Display allocated memory size")
	flagAllocObjects := flag.Bool("alloc_objects", false, "Display allocated object counts")
	// Contention profile options
	flagTotalDelay := flag.Bool("total_delay", false, "Display total delay at each region")
	flagContentions := flag.Bool("contentions", false, "Display number of delays at each region")
	flagMeanDelay := flag.Bool("mean_delay", false, "Display mean delay at each region")
	flagTools := flag.String("tools", os.Getenv("PPROF_TOOLS"), "Path for object tool pathnames")

	flagHTTP := flag.String("http", "", "Present interactive web UI at the specified http host:port")
	flagNoBrowser := flag.Bool("no_browser", false, "Skip opening a browswer for the interactive web UI")

	// Flags used during command processing
	installedFlags := installFlags(flag)

	flagCommands := make(map[string]*bool)
	flagParamCommands := make(map[string]*string)
	for name, cmd := range pprofCommands {
		if cmd.hasParam {
			flagParamCommands[name] = flag.String(name, "", "Generate a report in "+name+" format, matching regexp")
		} else {
			flagCommands[name] = flag.Bool(name, false, "Generate a report in "+name+" format")
		}
	}

	args := flag.Parse(func() {
		o.UI.Print(usageMsgHdr +
			usage(true) +
			usageMsgSrc +
			flag.ExtraUsage() +
			usageMsgVars)
	})
	if len(args) == 0 {
		return nil, nil, errors.New("no profile source specified")
	}

	var execName string
	// Recognize first argument as an executable or buildid override.
	if len(args) > 1 {
		arg0 := args[0]
		if file, err := o.Obj.Open(arg0, 0, ^uint64(0), 0); err == nil {
			file.Close()
			execName = arg0
			args = args[1:]
		} else if *flagBuildID == "" && isBuildID(arg0) {
			*flagBuildID = arg0
			args = args[1:]
		}
	}

	// Report conflicting options
	if err := updateFlags(installedFlags); err != nil {
		return nil, nil, err
	}

	cmd, err := outputFormat(flagCommands, flagParamCommands)
	if err != nil {
		return nil, nil, err
	}
	if cmd != nil && *flagHTTP != "" {
		return nil, nil, errors.New("-http is not compatible with an output format on the command line")
	}

	if *flagNoBrowser && *flagHTTP == "" {
		return nil, nil, errors.New("-no_browser only makes sense with -http")
	}

	si := pprofVariables["sample_index"].value
	si = sampleIndex(flagTotalDelay, si, "delay", "-total_delay", o.UI)
	si = sampleIndex(flagMeanDelay, si, "delay", "-mean_delay", o.UI)
	si = sampleIndex(flagContentions, si, "contentions", "-contentions", o.UI)
	si = sampleIndex(flagInUseSpace, si, "inuse_space", "-inuse_space", o.UI)
	si = sampleIndex(flagInUseObjects, si, "inuse_objects", "-inuse_objects", o.UI)
	si = sampleIndex(flagAllocSpace, si, "alloc_space", "-alloc_space", o.UI)
	si = sampleIndex(flagAllocObjects, si, "alloc_objects", "-alloc_objects", o.UI)
	pprofVariables.set("sample_index", si)

	if *flagMeanDelay {
		pprofVariables.set("mean", "true")
	}

	source := &source{
		Sources:            args,
		ExecName:           execName,
		BuildID:            *flagBuildID,
		Seconds:            *flagSeconds,
		Timeout:            *flagTimeout,
		Symbolize:          *flagSymbolize,
		HTTPHostport:       *flagHTTP,
		HTTPDisableBrowser: *flagNoBrowser,
		Comment:            *flagAddComment,
	}

	if err := source.addBaseProfiles(*flagBase, *flagDiffBase); err != nil {
		return nil, nil, err
	}

	normalize := pprofVariables["normalize"].boolValue()
	if normalize && len(source.Base) == 0 {
		return nil, nil, errors.New("must have base profile to normalize by")
	}
	source.Normalize = normalize

	if bu, ok := o.Obj.(*binutils.Binutils); ok {
		bu.SetTools(*flagTools)
	}
	return source, cmd, nil
}
146253
func (fl *Flags) Options() (auth.Options, error) {
	opts := fl.defaults
	opts.ServiceAccountJSONPath = fl.serviceAccountJSON
	if fl.RegisterScopesFlag {
		opts.Scopes = strings.Split(fl.scopes, " ")
		sort.Strings(opts.Scopes)
	}
	return opts, nil
}
16179
func JoinMountOptions(userOptions []string, systemOptions []string) []string {
	allMountOptions := sets.NewString()

	for _, mountOption := range userOptions {
		if len(mountOption) > 0 {
			allMountOptions.Insert(mountOption)
		}
	}

	for _, mountOption := range systemOptions {
		allMountOptions.Insert(mountOption)
	}
	return allMountOptions.List()
}
53169
func parseOptions(h http.Handler, opts ...Option) *csrf {
	// Set the handler to call after processing.
	cs := &csrf{
		h: h,
	}

	// Default to true. See Secure & HttpOnly function comments for rationale.
	// Set here to allow package users to override the default.
	cs.opts.Secure = true
	cs.opts.HttpOnly = true

	// Range over each options function and apply it
	// to our csrf type to configure it. Options functions are
	// applied in order, with any conflicting options overriding
	// earlier calls.
	for _, option := range opts {
		option(cs)
	}

	return cs
}
848562
func ParseTCPOptions(b []byte) TCPOptions {
	opts := TCPOptions{}
	limit := len(b)
	for i := 0; i < limit; {
		switch b[i] {
		case TCPOptionEOL:
			i = limit
		case TCPOptionNOP:
			i++
		case TCPOptionTS:
			if i+10 > limit || (b[i+1] != 10) {
				return opts
			}
			opts.TS = true
			opts.TSVal = binary.BigEndian.Uint32(b[i+2:])
			opts.TSEcr = binary.BigEndian.Uint32(b[i+6:])
			i += 10
		case TCPOptionSACK:
			if i+2 > limit {
				// Malformed SACK block, just return and stop parsing.
				return opts
			}
			sackOptionLen := int(b[i+1])
			if i+sackOptionLen > limit || (sackOptionLen-2)%8 != 0 {
				// Malformed SACK block, just return and stop parsing.
				return opts
			}
			numBlocks := (sackOptionLen - 2) / 8
			opts.SACKBlocks = []SACKBlock{}
			for j := 0; j < numBlocks; j++ {
				start := binary.BigEndian.Uint32(b[i+2+j*8:])
				end := binary.BigEndian.Uint32(b[i+2+j*8+4:])
				opts.SACKBlocks = append(opts.SACKBlocks, SACKBlock{
					Start: seqnum.Value(start),
					End:   seqnum.Value(end),
				})
			}
			i += sackOptionLen
		default:
			// We don't recognize this option, just skip over it.
			if i+2 > limit {
				return opts
			}
			l := int(b[i+1])
			// If the length is incorrect or if l+i overflows the
			// total options length then return false.
			if l < 2 || i+l > limit {
				return opts
			}
			i += l
		}
	}
	return opts
}
102506
func ParseSynOptions(opts []byte, isAck bool) TCPSynOptions {
	limit := len(opts)

	synOpts := TCPSynOptions{
		// Per RFC 1122, page 85: "If an MSS option is not received at
		// connection setup, TCP MUST assume a default send MSS of 536."
		MSS: 536,
		// If no window scale option is specified, WS in options is
		// returned as -1; this is because the absence of the option
		// indicates that the we cannot use window scaling on the
		// receive end either.
		WS: -1,
	}

	for i := 0; i < limit; {
		switch opts[i] {
		case TCPOptionEOL:
			i = limit
		case TCPOptionNOP:
			i++
		case TCPOptionMSS:
			if i+4 > limit || opts[i+1] != 4 {
				return synOpts
			}
			mss := uint16(opts[i+2])<<8 | uint16(opts[i+3])
			if mss == 0 {
				return synOpts
			}
			synOpts.MSS = mss
			i += 4

		case TCPOptionWS:
			if i+3 > limit || opts[i+1] != 3 {
				return synOpts
			}
			ws := int(opts[i+2])
			if ws > MaxWndScale {
				ws = MaxWndScale
			}
			synOpts.WS = ws
			i += 3

		case TCPOptionTS:
			if i+10 > limit || opts[i+1] != 10 {
				return synOpts
			}
			synOpts.TSVal = binary.BigEndian.Uint32(opts[i+2:])
			if isAck {
				// If the segment is a SYN-ACK then store the Timestamp Echo Reply
				// in the segment.
				synOpts.TSEcr = binary.BigEndian.Uint32(opts[i+6:])
			}
			synOpts.TS = true
			i += 10
		case TCPOptionSACKPermitted:
			if i+2 > limit || opts[i+1] != 2 {
				return synOpts
			}
			synOpts.SACKPermitted = true
			i += 2

		default:
			// We don't recognize this option, just skip over it.
			if i+2 > limit {
				return synOpts
			}
			l := int(opts[i+1])
			// If the length is incorrect or if l+i overflows the
			// total options length then return false.
			if l < 2 || i+l > limit {
				return synOpts
			}
			i += l
		}
	}

	return synOpts
}
988452
func appendDefaultMountOptions(mountOptions []string, fsGroup *int64) []string {
	fileModeFlag := false
	dirModeFlag := false
	versFlag := false
	gidFlag := false

	for _, mountOption := range mountOptions {
		if strings.HasPrefix(mountOption, fileMode) {
			fileModeFlag = true
		}
		if strings.HasPrefix(mountOption, dirMode) {
			dirModeFlag = true
		}
		if strings.HasPrefix(mountOption, vers) {
			versFlag = true
		}
		if strings.HasPrefix(mountOption, gid) {
			gidFlag = true
		}
	}

	allMountOptions := mountOptions
	if !fileModeFlag {
		allMountOptions = append(allMountOptions, fmt.Sprintf("%s=%s", fileMode, defaultFileMode))
	}

	if !dirModeFlag {
		allMountOptions = append(allMountOptions, fmt.Sprintf("%s=%s", dirMode, defaultDirMode))
	}

	if !versFlag {
		allMountOptions = append(allMountOptions, fmt.Sprintf("%s=%s", vers, defaultVers))
	}

	if !gidFlag && fsGroup != nil {
		allMountOptions = append(allMountOptions, fmt.Sprintf("%s=%d", gid, *fsGroup))
	}
	return allMountOptions
}
618117
func ParseFiles(fs []string) (*Source, error) {
	src := &Source{
		Funcs: make([]*Fn, 0),
		Files: make([]string, 0),
		StdLibImports: []string{
			"unsafe",
		},
		ExternalImports: make([]string, 0),
	}
	for _, file := range fs {
		if err := src.ParseFile(file); err != nil {
			return nil, err
		}
	}
	return src, nil
}
511616
func (b *EtcdOptionsBuilder) BuildOptions(o interface{}) error {
	spec := o.(*kops.ClusterSpec)

	for _, c := range spec.EtcdClusters {
		if c.Provider == "" {
			if b.IsKubernetesGTE("1.12") {
				c.Provider = kops.EtcdProviderTypeManager
			} else if c.Manager != nil {
				c.Provider = kops.EtcdProviderTypeManager
			} else {
				c.Provider = kops.EtcdProviderTypeLegacy
			}
		}

		// Ensure the version is set
		if c.Version == "" && c.Provider == kops.EtcdProviderTypeLegacy {
			// Even if in legacy mode, etcd version 2 is unsupported as of k8s 1.13
			if b.IsKubernetesGTE("1.13") {
				c.Version = DefaultEtcd3Version_1_13
			} else {
				c.Version = DefaultEtcd2Version
			}
		}

		if c.Version == "" && c.Provider == kops.EtcdProviderTypeManager {
			// From 1.11, we run the k8s-recommended versions of etcd when using the manager
			if b.IsKubernetesGTE("1.11") {
				c.Version = DefaultEtcd3Version_1_11
			} else {
				c.Version = DefaultEtcd2Version
			}
		}

		// From 1.12, we enable TLS if we're running EtcdManager & etcd3
		//
		// (Moving to etcd3 is a disruptive upgrade, so we
		// force TLS at the same time as we enable
		// etcd-manager by default).
		if c.Provider == kops.EtcdProviderTypeManager {
			etcdV3 := true
			version := c.Version
			version = strings.TrimPrefix(version, "v")
			if strings.HasPrefix(version, "2.") {
				etcdV3 = false
			} else if strings.HasPrefix(version, "3.") {
				etcdV3 = true
			} else {
				return fmt.Errorf("unexpected etcd version %q", c.Version)
			}

			if b.IsKubernetesGTE("1.12.0") && etcdV3 {
				c.EnableEtcdTLS = true
				c.EnableTLSAuth = true
			}
		}
	}

	// Remap the well known images
	for _, c := range spec.EtcdClusters {

		// We remap the etcd manager image when we build the manifest,
		// but we need to map the standalone images here because protokube launches them

		if c.Provider == kops.EtcdProviderTypeLegacy {

			// remap etcd image
			{
				image := c.Image
				if image == "" {
					image = fmt.Sprintf("k8s.gcr.io/etcd:%s", c.Version)
				}

				if image != "" {
					image, err := b.AssetBuilder.RemapImage(image)
					if err != nil {
						return fmt.Errorf("unable to remap container %q: %v", image, err)
					}
					c.Image = image
				}
			}

			// remap backup manager image
			if c.Backups != nil {
				image := c.Backups.Image
				if image == "" {
					image = fmt.Sprintf(DefaultBackupImage)
				}

				if image != "" {
					image, err := b.AssetBuilder.RemapImage(image)
					if err != nil {
						return fmt.Errorf("unable to remap container %q: %v", image, err)
					}
					c.Backups.Image = image
				}
			}
		}
	}

	return nil
}
1296883
func parseKeyForOption(key string) (string, []string) {
	opts := strings.Split(key, ",")
	return opts[0], opts[1:]
}