LoadLibraryImpl - loads a single library to memory, without trying to check or load required imports
(name string, image *[]byte)
| 13 | |
| 14 | // LoadLibraryImpl - loads a single library to memory, without trying to check or load required imports |
| 15 | func LoadLibraryImpl(name string, image *[]byte) (*Library, error) { |
| 16 | elflib, err := elf.NewFile(bytes.NewReader(*image)) |
| 17 | if err != nil { |
| 18 | return nil, err |
| 19 | } |
| 20 | if elflib.FileHeader.Type != elf.ET_DYN { |
| 21 | return nil, errors.New("Cannot load non-dynamic libraries") |
| 22 | } |
| 23 | exports, err := elflib.Exports() |
| 24 | if err != nil { |
| 25 | return nil, err |
| 26 | } |
| 27 | pageSize := uint64(unix.Getpagesize()) |
| 28 | var memSize uint64 |
| 29 | |
| 30 | loads := make([]*elf.Prog, 0) |
| 31 | for _, p := range elflib.Progs { |
| 32 | if p.Type != elf.PT_LOAD || p.Filesz == 0 || p.Memsz == 0 { |
| 33 | continue |
| 34 | } |
| 35 | highest := p.Memsz + p.Vaddr |
| 36 | if highest > memSize { |
| 37 | memSize = highest |
| 38 | } |
| 39 | loads = append(loads, p) |
| 40 | } |
| 41 | if memSize%pageSize != 0 { // round up to page size |
| 42 | memSize = ((memSize / pageSize) * pageSize) + pageSize |
| 43 | } |
| 44 | baseBuf, err := unix.Mmap(-1, 0, int(memSize), |
| 45 | unix.PROT_READ|unix.PROT_WRITE|unix.PROT_EXEC, unix.MAP_PRIVATE|unix.MAP_ANON) |
| 46 | if err != nil { |
| 47 | return nil, err |
| 48 | } |
| 49 | for _, p := range loads { |
| 50 | copy(baseBuf[p.Vaddr:], (*image)[p.Off:p.Off+p.Filesz]) |
| 51 | } |
| 52 | ex := make(map[string]uint64) |
| 53 | for _, x := range exports { |
| 54 | ex[x.Name] = x.VirtualAddress |
| 55 | } |
| 56 | library := Library{ |
| 57 | BaseAddress: uintptr(unsafe.Pointer(&baseBuf[0])), |
| 58 | Exports: ex, |
| 59 | } |
| 60 | return &library, nil |
| 61 | } |
| 62 | |
| 63 | // Call - call a function in a loaded library |
| 64 | func (l *Library) Call(functionName string, args ...uintptr) (uintptr, error) { |
no outgoing calls
no test coverage detected
searching dependent graphs…