golang 从编译文件中获取所有文件路径

我正在尝试获取在编译期间使用的所有源文件。函数 runtime.Caller() 和带有堆栈跟踪的恐慌显示此信息。


我需要这样的东西


func fetchUsedFiles() []string {

    ....

}

func main() {

    log.Println("Used Files",fetchUsedFiles())

}

UPS:


我需要的只是以某种方式读取“runtime.firstmoduledata”变量内容。但它不是导出变量。


米琪卡哇伊
浏览 196回答 1
1回答

凤凰求蛊

实际上,我已经结合了 VonC 答案和我的运行时方法。所有需要的数据都存储在runtime.firstmoduledata- struct 但它们不会被导出。要从那里读取数据,我再次读取我的可执行文件(仅针对 ELF 实现),找到此符号并执行其他部分,如 runtime.Caller() 函数。此方法不可移植,并且可以通过运行时库中的更改来破坏,但它可以工作。selfReflect 函数使用运行时库中私有类型的副本https://github.com/martende/restartable/blob/master/restartable.go#L208func selfReflect(filename string) ([]string,error) {&nbsp; &nbsp; f,err := elf.Open(filename)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil,err&nbsp; &nbsp; }&nbsp; &nbsp; defer f.Close()&nbsp; &nbsp; syms,err := f.Symbols()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil,err&nbsp; &nbsp; }&nbsp; &nbsp; var modSym elf.Symbol&nbsp; &nbsp; var modSymFound = false&nbsp; &nbsp; for _,v := range syms {&nbsp; &nbsp; &nbsp; &nbsp; if v.Name == "runtime.firstmoduledata" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; modSym = v&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; modSymFound = true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if ! modSymFound {&nbsp; &nbsp; &nbsp; &nbsp; return nil,errors.New("elfparse:nosym")&nbsp; &nbsp; }&nbsp; &nbsp; var datap = (*moduledata)(unsafe.Pointer(uintptr(modSym.Value)))&nbsp; &nbsp; files := make([]string,0)&nbsp; &nbsp; for i := range datap.filetab {&nbsp; &nbsp; &nbsp; &nbsp; bp := &datap.pclntable[datap.filetab[i]]&nbsp; &nbsp; &nbsp; &nbsp; file := C.GoString( (*C.char) (unsafe.Pointer(bp))&nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; if file != "<autogenerated>" && file != "@" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if _, err := os.Stat(file); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; files = append(files ,file)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return files,nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go