package addr2line

import (
	"strconv"

	. "ios-wrapper/pkg/ios/macho"
)

// Try to get Image base of a DWARF binary
// using __mh_execute_header symbol
func TryGetImageBase(mc *MachoContext, symbols []*Symbol) uint64 {
	try := mc.ImageBase()
	if try != 0 {
		return try
	}
	for _, symbol := range symbols {
		if symbol.Name() == "__mh_execute_header" {
			return symbol.Address()
		}
	}
	return 0
}

// find the symbol name from dysymtab
// the address given is somewhere in the function,
// assuming that the address is sorted, we find the last symbol
// has its address smaller than `tofind`
// I'm not sure this would work always, ;)
func FindSymbol(symbols []*Symbol, tofind uint64) string {
	var lastSymbol string = ""
	for _, symbol := range symbols {
		if symbol.Address() > tofind {
			return lastSymbol
		} else {
			lastSymbol = symbol.Name()
		}
	}
	return ""
}

func ParseAddressString(s string) (uint64, error) {
	s_, err := strconv.ParseInt(s, 0, 64)
	v := uint64(s_)
	if err != nil {
		return 0, err
	}
	return v, nil
}