MCPcopy Create free account
hub / github.com/Binject/universal / LoadLibraryImpl

Function LoadLibraryImpl

loader_windows.go:24–71  ·  view source on GitHub ↗

LoadLibraryImpl - loads a single library to memory, without trying to check or load required imports

(name string, image *[]byte)

Source from the content-addressed store, hash-verified

22
23// LoadLibraryImpl - loads a single library to memory, without trying to check or load required imports
24func LoadLibraryImpl(name string, image *[]byte) (*Library, error) {
25 const PtrSize = 32 << uintptr(^uintptr(0)>>63) // are we on a 32bit or 64bit system?
26 pelib, err := pe.NewFile(bytes.NewReader(*image))
27 if err != nil {
28 return nil, err
29 }
30 pe64 := pelib.Machine == pe.IMAGE_FILE_MACHINE_AMD64
31 if pe64 && PtrSize != 64 {
32 return nil, errors.New("Cannot load a 64bit DLL from a 32bit process")
33 } else if !pe64 && PtrSize != 32 {
34 return nil, errors.New("Cannot load a 32bit DLL from a 64bit process")
35 }
36
37 var sizeOfImage uint32
38 if pe64 {
39 sizeOfImage = pelib.OptionalHeader.(*pe.OptionalHeader64).SizeOfImage
40 } else {
41 sizeOfImage = pelib.OptionalHeader.(*pe.OptionalHeader32).SizeOfImage
42 }
43 r, err := virtualAlloc(0, sizeOfImage, MEM_RESERVE, syscall.PAGE_READWRITE)
44 if err != nil {
45 return nil, err
46 }
47 dst, err := virtualAlloc(r, sizeOfImage, MEM_COMMIT, syscall.PAGE_EXECUTE_READWRITE)
48 if err != nil {
49 return nil, err
50 }
51
52 //perform base relocations
53 pelib.Relocate(uint64(dst), image)
54
55 //write to memory
56 CopySections(pelib, image, dst)
57
58 exports, err := pelib.Exports()
59 if err != nil {
60 return nil, err
61 }
62 lib := Library{
63 BaseAddress: dst,
64 Exports: make(map[string]uint64),
65 }
66 for _, x := range exports {
67 lib.Exports[x.Name] = uint64(x.VirtualAddress)
68 }
69
70 return &lib, nil
71}
72
73// CopySections - writes the sections of a PE image to the given base address in memory
74func CopySections(pefile *pe.File, image *[]byte, loc uintptr) error {

Callers

nothing calls this directly

Calls 2

virtualAllocFunction · 0.85
CopySectionsFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…