douhui0975 2016-05-16 09:52 采纳率: 100%
浏览 277
已采纳

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

I am trying to fetch all source files that where used during compilation. Function runtime.Caller() and panic with its stacktrace show this info.

I need something like this

func fetchUsedFiles() []string {
    ....
}
func main() {
    log.Println("Used Files",fetchUsedFiles())
}

UPD:

All what I need is read somehow "runtime.firstmoduledata" variable content. But it is not exported variable.

  • 写回答

1条回答 默认 最新

  • duanlin6989 2016-05-18 07:27
    关注

    Actually I have combined VonC answer and my runtime approcah.

    All needed data stored at runtime.firstmoduledata - struct but they are not exported. To read data from there I read my executable file again (implemented only for ELF), find this symbol and do the other part like runtime.Caller() function. This method is not portable and can be broken by changes in runtime library but it works.

    selfReflect function uses copies of private types from runtime lib

    https://github.com/martende/restartable/blob/master/restartable.go#L208

    func selfReflect(filename string) ([]string,error) {
        f,err := elf.Open(filename)
        if err != nil {
            return nil,err
        }
        defer f.Close()
        syms,err := f.Symbols()
        if err != nil {
            return nil,err
        }
        var modSym elf.Symbol
        var modSymFound = false
        for _,v := range syms {
            if v.Name == "runtime.firstmoduledata" {
                modSym = v
                modSymFound = true
                break
            }
        }
        if ! modSymFound {
            return nil,errors.New("elfparse:nosym")
        }
    
        var datap = (*moduledata)(unsafe.Pointer(uintptr(modSym.Value)))
    
        files := make([]string,0)
        for i := range datap.filetab {
            bp := &datap.pclntable[datap.filetab[i]]
            file := C.GoString( (*C.char) (unsafe.Pointer(bp))  )
            if file != "<autogenerated>" && file != "@" {
                if _, err := os.Stat(file); err == nil {
                    files = append(files ,file)
                }
            }
        }
    
    
        return files,nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题