Created
January 19, 2021 15:00
-
-
Save khyberspache/d040c627aece5b1b2adeb59ffa7734d9 to your computer and use it in GitHub Desktop.
Define commands build for Windows platforms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package commands | |
import ( | |
"encoding/json" | |
"log" | |
"os" | |
"syscall" | |
"unsafe" | |
) | |
func CallNativeAPI(task string) (string, int, int) { | |
switch task { | |
case "ps": | |
log.Print("Running Task") | |
return getProcesses() | |
} | |
return "not implemented", 1, os.Getpid() | |
} | |
type WindowsProcess struct { | |
ProcessID int | |
ParentProcessID int | |
ExeFile string | |
} | |
func getProcesses() (string, int, int) { | |
procs, _ := getProcessWindowsProcesses() | |
data, err := json.Marshal(procs) | |
if err != nil { | |
log.Print("Failed") | |
return "Failed serializing processes", 1, os.Getpid() | |
} | |
return string(data), 0, os.Getpid() | |
} | |
func getProcessWindowsProcesses() ([]WindowsProcess, error) { | |
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0) | |
if err != nil { | |
return nil, err | |
} | |
defer syscall.CloseHandle(snapshot) | |
var procEntry syscall.ProcessEntry32 | |
procEntry.Size = uint32(unsafe.Sizeof(procEntry)) | |
if err = syscall.Process32First(snapshot, &procEntry); err != nil { | |
return nil, err | |
} | |
processes := make([]WindowsProcess, 0, 100) | |
for { | |
processes = append(processes, newWindowsProcess(&procEntry)) | |
if err = syscall.Process32Next(snapshot, &procEntry); err != nil { | |
if err == syscall.ERROR_NO_MORE_FILES { | |
break | |
} | |
} | |
} | |
return processes, nil | |
} | |
func newWindowsProcess(e *syscall.ProcessEntry32) WindowsProcess { | |
end := getProcessNameLength(e) | |
return WindowsProcess{ | |
ProcessID: int(e.ProcessID), | |
ParentProcessID: int(e.ParentProcessID), | |
ExeFile: syscall.UTF16ToString(e.ExeFile[:end]), | |
} | |
} | |
func getProcessNameLength(e *syscall.ProcessEntry32) int { | |
size := 0 | |
for _, char := range e.ExeFile { | |
if char == 0 { | |
break | |
} | |
size++ | |
} | |
return size | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment