ldd: separate Parse from Exec and trim space

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
This commit is contained in:
2024-10-09 23:51:15 +09:00
parent 22dfa73efe
commit d41b9d2d9c
5 changed files with 139 additions and 31 deletions

View File

@@ -1,49 +1,31 @@
package ldd
import (
"errors"
"fmt"
"math"
"os"
"os/exec"
"path"
"strconv"
"strings"
)
var (
ErrUnexpectedSeparator = errors.New("unexpected separator")
ErrPathNotAbsolute = errors.New("path not absolute")
ErrBadLocationFormat = errors.New("bad location format")
)
type Entry struct {
Name string `json:"name,omitempty"`
Path string `json:"path,omitempty"`
Location uint64 `json:"location"`
}
func Exec(p string) ([]*Entry, error) {
t := exec.Command("ldd", p)
t.Stdout = new(strings.Builder)
t.Stderr = os.Stderr
if err := t.Run(); err != nil {
return nil, err
}
out := t.Stdout.(fmt.Stringer).String()
payload := strings.Split(out, "\n")
func Parse(stdout fmt.Stringer) ([]*Entry, error) {
payload := strings.Split(strings.TrimSpace(stdout.String()), "\n")
result := make([]*Entry, len(payload))
for i, ent := range payload {
if len(ent) == 0 {
continue
return nil, ErrUnexpectedNewline
}
segment := strings.SplitN(ent, " ", 5)
// location index
var iL int
switch len(segment) {
@@ -63,7 +45,7 @@ func Exec(p string) ([]*Entry, error) {
Path: segment[2],
}
default:
return nil, &EntryUnexpectedSegmentsError{ent}
return nil, EntryUnexpectedSegmentsError(ent)
}
if loc, err := parseLocation(segment[iL]); err != nil {