// Copyright 2018 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package procfs

import (
	
	
	
	
	
	
	

	
)

// Proc provides information about a running process.
type Proc struct {
	// The process ID.
	PID int

	fs FS
}

// Procs represents a list of Proc structs.
type Procs []Proc

var (
	ErrFileParse  = errors.New("error parsing file")
	ErrFileRead   = errors.New("error reading file")
	ErrMountPoint = errors.New("error accessing mount point")
)

func ( Procs) () int           { return len() }
func ( Procs) (,  int)      { [], [] = [], [] }
func ( Procs) (,  int) bool { return [].PID < [].PID }

// Self returns a process for the current process read via /proc/self.
func () (Proc, error) {
	,  := NewFS(DefaultMountPoint)
	if  != nil || errors.Unwrap() == ErrMountPoint {
		return Proc{}, 
	}
	return .Self()
}

// NewProc returns a process for the given pid under /proc.
func ( int) (Proc, error) {
	,  := NewFS(DefaultMountPoint)
	if  != nil {
		return Proc{}, 
	}
	return .Proc()
}

// AllProcs returns a list of all currently available processes under /proc.
func () (Procs, error) {
	,  := NewFS(DefaultMountPoint)
	if  != nil {
		return Procs{}, 
	}
	return .AllProcs()
}

// Self returns a process for the current process.
func ( FS) () (Proc, error) {
	,  := os.Readlink(.proc.Path("self"))
	if  != nil {
		return Proc{}, 
	}
	,  := strconv.Atoi(strings.ReplaceAll(, string(.proc), ""))
	if  != nil {
		return Proc{}, 
	}
	return .Proc()
}

// NewProc returns a process for the given pid.
//
// Deprecated: Use fs.Proc() instead.
func ( FS) ( int) (Proc, error) {
	return .Proc()
}

// Proc returns a process for the given pid.
func ( FS) ( int) (Proc, error) {
	if ,  := os.Stat(.proc.Path(strconv.Itoa()));  != nil {
		return Proc{}, 
	}
	return Proc{PID: , fs: }, nil
}

// AllProcs returns a list of all currently available processes.
func ( FS) () (Procs, error) {
	,  := os.Open(.proc.Path())
	if  != nil {
		return Procs{}, 
	}
	defer .Close()

	,  := .Readdirnames(-1)
	if  != nil {
		return Procs{}, fmt.Errorf("%w: Cannot read file: %v: %w", ErrFileRead, , )
	}

	 := Procs{}
	for ,  := range  {
		,  := strconv.ParseInt(, 10, 64)
		if  != nil {
			continue
		}
		 = append(, Proc{PID: int(), fs: })
	}

	return , nil
}

// CmdLine returns the command line of a process.
func ( Proc) () ([]string, error) {
	,  := util.ReadFileNoStat(.path("cmdline"))
	if  != nil {
		return nil, 
	}

	if len() < 1 {
		return []string{}, nil
	}

	return strings.Split(string(bytes.TrimRight(, "\x00")), "\x00"), nil
}

// Wchan returns the wchan (wait channel) of a process.
func ( Proc) () (string, error) {
	,  := os.Open(.path("wchan"))
	if  != nil {
		return "", 
	}
	defer .Close()

	,  := io.ReadAll()
	if  != nil {
		return "", 
	}

	 := string()
	if  == "" ||  == "0" {
		return "", nil
	}

	return , nil
}

// Comm returns the command name of a process.
func ( Proc) () (string, error) {
	,  := util.ReadFileNoStat(.path("comm"))
	if  != nil {
		return "", 
	}

	return strings.TrimSpace(string()), nil
}

// Executable returns the absolute path of the executable command of a process.
func ( Proc) () (string, error) {
	,  := os.Readlink(.path("exe"))
	if os.IsNotExist() {
		return "", nil
	}

	return , 
}

// Cwd returns the absolute path to the current working directory of the process.
func ( Proc) () (string, error) {
	,  := os.Readlink(.path("cwd"))
	if os.IsNotExist() {
		return "", nil
	}

	return , 
}

// RootDir returns the absolute path to the process's root directory (as set by chroot).
func ( Proc) () (string, error) {
	,  := os.Readlink(.path("root"))
	if os.IsNotExist() {
		return "", nil
	}

	return , 
}

// FileDescriptors returns the currently open file descriptors of a process.
func ( Proc) () ([]uintptr, error) {
	,  := .fileDescriptors()
	if  != nil {
		return nil, 
	}

	 := make([]uintptr, len())
	for ,  := range  {
		,  := strconv.ParseInt(, 10, 32)
		if  != nil {
			return nil, fmt.Errorf("%w: Cannot parse line: %v: %w", ErrFileParse, , )
		}
		[] = uintptr()
	}

	return , nil
}

// FileDescriptorTargets returns the targets of all file descriptors of a process.
// If a file descriptor is not a symlink to a file (like a socket), that value will be the empty string.
func ( Proc) () ([]string, error) {
	,  := .fileDescriptors()
	if  != nil {
		return nil, 
	}

	 := make([]string, len())

	for ,  := range  {
		,  := os.Readlink(.path("fd", ))
		if  == nil {
			[] = 
		}
	}

	return , nil
}

// FileDescriptorsLen returns the number of currently open file descriptors of
// a process.
func ( Proc) () (int, error) {
	// Use fast path if available (Linux v6.2): https://github.com/torvalds/linux/commit/f1f1f2569901
	if .fs.isReal {
		,  := os.Stat(.path("fd"))
		if  != nil {
			return 0, 
		}

		 := .Size()
		if  > 0 {
			return int(), nil
		}
	}

	,  := .fileDescriptors()
	if  != nil {
		return 0, 
	}

	return len(), nil
}

// MountStats retrieves statistics and configuration for mount points in a
// process's namespace.
func ( Proc) () ([]*Mount, error) {
	,  := os.Open(.path("mountstats"))
	if  != nil {
		return nil, 
	}
	defer .Close()

	return parseMountStats()
}

// MountInfo retrieves mount information for mount points in a
// process's namespace.
// It supplies information missing in `/proc/self/mounts` and
// fixes various other problems with that file too.
func ( Proc) () ([]*MountInfo, error) {
	,  := util.ReadFileNoStat(.path("mountinfo"))
	if  != nil {
		return nil, 
	}
	return parseMountInfo()
}

func ( Proc) () ([]string, error) {
	,  := os.Open(.path("fd"))
	if  != nil {
		return nil, 
	}
	defer .Close()

	,  := .Readdirnames(-1)
	if  != nil {
		return nil, fmt.Errorf("%w: Cannot read file: %v: %w", ErrFileRead, , )
	}

	return , nil
}

func ( Proc) ( ...string) string {
	return .fs.proc.Path(append([]string{strconv.Itoa(.PID)}, ...)...)
}

// FileDescriptorsInfo retrieves information about all file descriptors of
// the process.
func ( Proc) () (ProcFDInfos, error) {
	,  := .fileDescriptors()
	if  != nil {
		return nil, 
	}

	var  ProcFDInfos

	for ,  := range  {
		,  := .FDInfo()
		if  != nil {
			continue
		}
		 = append(, *)
	}

	return , nil
}

// Schedstat returns task scheduling information for the process.
func ( Proc) () (ProcSchedstat, error) {
	,  := os.ReadFile(.path("schedstat"))
	if  != nil {
		return ProcSchedstat{}, 
	}
	return parseProcSchedstat(string())
}