| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package containers
- import (
- "debug/elf"
- "fmt"
- "io/ioutil"
- "log"
- "os"
- "os/exec"
- "regexp"
- "runtime"
- )
- var libjvmRegex = regexp.MustCompile(`.*/libjvm\.so`)
- func GetExeType(pid uint32) CodeType {
- mapsFilePath := fmt.Sprintf("/proc/%d/maps", pid)
- data, err := ioutil.ReadFile(mapsFilePath)
- if err != nil {
- log.Fatalf("Failed to read %s: %s", mapsFilePath, err)
- }
- content := string(data)
- if libjvmRegex.MatchString(content) {
- fmt.Println("is java process")
- return CodeTypeJava
- } else if isGoProcess(pid) {
- return CodeTypeGo
- fmt.Println("is go process")
- }
- return CodeTypeUnknown
- }
- func isGoProcess(pid uint32) bool {
- path, err := getProcessPath(pid)
- if err != nil {
- fmt.Printf("无法获取进程路径:%s\n", err)
- return false
- }
- ef, err := elf.Open(path)
- if err != nil {
- fmt.Println("failed to open as elf binary", err)
- return false
- }
- defer ef.Close()
- gopclntabSection := ef.Section(".gopclntab")
- if gopclntabSection != nil {
- fmt.Println("is a go process")
- return true
- }
- return false
- }
- func getProcessPath(pid uint32) (string, error) {
- switch runtime.GOOS {
- case "linux":
- return getLinuxProcessPath(pid)
- default:
- return "", fmt.Errorf("不支持的操作系统:%s", runtime.GOOS)
- }
- }
- func getLinuxProcessPath(pid uint32) (string, error) {
- procPath := fmt.Sprintf("/proc/%d/exe", pid)
- path, err := os.Readlink(procPath)
- if err != nil {
- return "", err
- }
- return path, nil
- }
- func executeCommand(name string, args ...string) (string, error) {
- cmd := exec.Command(name, args...)
- out, err := cmd.Output()
- if err != nil {
- return "", err
- }
- return string(out), nil
- }
|